C++ fwrite 不写入文本文件,不知道为什么?

发布于 2024-12-02 14:49:53 字数 1404 浏览 1 评论 0原文

我有这段代码,基本上从文件读取并创建新文件,并将内容从源写入目标文件。它读取缓冲区并创建文件,但 fwrite
不将内容写入新创建的文件,我不知道为什么。
这是代码。 (我只能将其与 _sopen 一起使用,它是遗留代码的一部分)

#include <stdio.h>
#include <stdlib.h>
#include <io.h>
#include <fcntl.h>
#include <string>
#include <share.h>
#include <sys\stat.h>


int main () {
  std::string szSource = "H:\\cpp\\test1.txt";
  FILE* pfFile;
  int iFileId = _sopen(szSource.c_str(),_O_RDONLY, _SH_DENYNO, _S_IREAD);
  if (iFileId >= 0) 
     pfFile = fdopen(iFileId, "r");
   //read file content to buffer 
   char * buffer;
   size_t result;
   long lSize;
   // obtain file size:
   fseek (pfFile , 0 , SEEK_END);
   lSize = ftell (pfFile);
   fseek(pfFile, 0, SEEK_SET);
 //   buffer = (char*) malloc (sizeof(char)*lSize);
   buffer = (char*) malloc (sizeof(char)*lSize);

   if (buffer == NULL)
   {

       return false;
   }

   // copy the file into the buffer:
   result = fread (buffer,lSize,1,pfFile);   
   std::string szdes = "H:\\cpp\\test_des.txt";
   FILE* pDesfFile;
   int iFileId2 = _sopen(szdes.c_str(),_O_CREAT,_SH_DENYNO,_S_IREAD | _S_IWRITE);
  if (iFileId2 >= 0) 
     pDesfFile = fdopen(iFileId2, "w+");

   size_t f = fwrite (buffer , 1, sizeof(buffer),pDesfFile );
   printf("Error code: %d\n",ferror(pDesfFile));

   fclose (pDesfFile);

  return 0;
}

您可以创建主文件并尝试它,看看它是否适合您。
谢谢

I have this code that basically reads from file and creates new file and write the content from the source to the destination file. It reads the buffer and creates the file, but fwrite
doesn't write the content to the newly created file, I have no idea why.
here is the code. (I have to use only this with _sopen, its part of legacy code)

#include <stdio.h>
#include <stdlib.h>
#include <io.h>
#include <fcntl.h>
#include <string>
#include <share.h>
#include <sys\stat.h>


int main () {
  std::string szSource = "H:\\cpp\\test1.txt";
  FILE* pfFile;
  int iFileId = _sopen(szSource.c_str(),_O_RDONLY, _SH_DENYNO, _S_IREAD);
  if (iFileId >= 0) 
     pfFile = fdopen(iFileId, "r");
   //read file content to buffer 
   char * buffer;
   size_t result;
   long lSize;
   // obtain file size:
   fseek (pfFile , 0 , SEEK_END);
   lSize = ftell (pfFile);
   fseek(pfFile, 0, SEEK_SET);
 //   buffer = (char*) malloc (sizeof(char)*lSize);
   buffer = (char*) malloc (sizeof(char)*lSize);

   if (buffer == NULL)
   {

       return false;
   }

   // copy the file into the buffer:
   result = fread (buffer,lSize,1,pfFile);   
   std::string szdes = "H:\\cpp\\test_des.txt";
   FILE* pDesfFile;
   int iFileId2 = _sopen(szdes.c_str(),_O_CREAT,_SH_DENYNO,_S_IREAD | _S_IWRITE);
  if (iFileId2 >= 0) 
     pDesfFile = fdopen(iFileId2, "w+");

   size_t f = fwrite (buffer , 1, sizeof(buffer),pDesfFile );
   printf("Error code: %d\n",ferror(pDesfFile));

   fclose (pDesfFile);

  return 0;
}

You can make main file and try it see if its working for you .
Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

反话 2024-12-09 14:49:53

将您的代码更改为以下内容,然后报告您的结果:

int main () {
  std::string szSource = "H:\\cpp\\test1.txt";
  int iFileId = _sopen(szSource.c_str(),_O_RDONLY, _SH_DENYNO, _S_IREAD);
  if (iFileId >= 0) 
  {
    FILE* pfFile;
    if ((pfFile = fdopen(iFileId, "r")) != (FILE *)NULL)
    {
      //read file content to buffer 
      char * buffer;
      size_t result;
      long lSize;
      // obtain file size:
      fseek (pfFile , 0 , SEEK_END);
      lSize = ftell (pfFile);
      fseek(pfFile, 0, SEEK_SET);
      if ((buffer = (char*) malloc (lSize)) == NULL)
        return false;

      // copy the file into the buffer:
      result = fread (buffer,(size_t)lSize,1,pfFile);   
      fclose(pfFile);

      std::string szdes = "H:\\cpp\\test_des.txt";
      FILE* pDesfFile;
      int iFileId2 = _sopen(szdes.c_str(),_O_CREAT,_SH_DENYNO,_S_IREAD | _S_IWRITE);
      if (iFileId2 >= 0) 
      {
        if ((pDesfFile = fdopen(iFileId2, "w+")) != (FILE *)NULL)
        {
          size_t f = fwrite (buffer, (size_t)lSize, 1, pDesfFile);
          printf ("elements written <%d>\n", f);

          if (f == 0)
            printf("Error code: %d\n",ferror(pDesfFile));

          fclose (pDesfFile);
        }
      }
    }
  }

  return 0;
}

[编辑]

对于其他发帖者,显示 fwrite 的用法/结果 - 以下的输出是什么?

#include <stdio.h>

int main (int argc, char **argv) {
   FILE *fp = fopen ("f.kdt", "w+");

   printf ("wrote %d\n", fwrite ("asdf", 4, 1, fp));

   fclose (fp);
}

[/编辑]

Change your code to the following and then report your results:

int main () {
  std::string szSource = "H:\\cpp\\test1.txt";
  int iFileId = _sopen(szSource.c_str(),_O_RDONLY, _SH_DENYNO, _S_IREAD);
  if (iFileId >= 0) 
  {
    FILE* pfFile;
    if ((pfFile = fdopen(iFileId, "r")) != (FILE *)NULL)
    {
      //read file content to buffer 
      char * buffer;
      size_t result;
      long lSize;
      // obtain file size:
      fseek (pfFile , 0 , SEEK_END);
      lSize = ftell (pfFile);
      fseek(pfFile, 0, SEEK_SET);
      if ((buffer = (char*) malloc (lSize)) == NULL)
        return false;

      // copy the file into the buffer:
      result = fread (buffer,(size_t)lSize,1,pfFile);   
      fclose(pfFile);

      std::string szdes = "H:\\cpp\\test_des.txt";
      FILE* pDesfFile;
      int iFileId2 = _sopen(szdes.c_str(),_O_CREAT,_SH_DENYNO,_S_IREAD | _S_IWRITE);
      if (iFileId2 >= 0) 
      {
        if ((pDesfFile = fdopen(iFileId2, "w+")) != (FILE *)NULL)
        {
          size_t f = fwrite (buffer, (size_t)lSize, 1, pDesfFile);
          printf ("elements written <%d>\n", f);

          if (f == 0)
            printf("Error code: %d\n",ferror(pDesfFile));

          fclose (pDesfFile);
        }
      }
    }
  }

  return 0;
}

[edit]

for other posters, to show the usage/results of fwrite - what is the output of the following?

#include <stdio.h>

int main (int argc, char **argv) {
   FILE *fp = fopen ("f.kdt", "w+");

   printf ("wrote %d\n", fwrite ("asdf", 4, 1, fp));

   fclose (fp);
}

[/edit]

红墙和绿瓦 2024-12-09 14:49:53

sizeof(buffer) 是指针的大小,即 4,而不是缓冲区中的项目数。

如果 buffer 是一个数组,则 sizeof(buffer) 可能会起作用,因为它返回数组中的字节数。

sizeof(buffer) is the size of the pointer, i.e. 4 and not the number of items in the buffer

If buffer is an array then sizeof(buffer) would potentially work as it returns the number of bytes in the array.

懒的傷心 2024-12-09 14:49:53

fwrite 的第三个参数是 sizeof(buffer),它是 4 个字节(一个指针)。您需要传入要写入的字节数(lSize)。

更新:看起来您还缺少指示文件应该读/写的标志:_O_RDWR

这对我有用......

   std::string szdes = "C:\\temp\\test_des.txt"; 
   FILE* pDesfFile; 
   int iFileId2;
   err = _sopen_s(&iFileId2, szdes.c_str(), _O_CREAT|_O_BINARY|_O_RDWR, _SH_DENYNO, _S_IREAD | _S_IWRITE); 
   if (iFileId2 >= 0)  
      pDesfFile = _fdopen(iFileId2, "w+"); 

   size_t f = fwrite (buffer , 1, lSize, pDesfFile ); 
   fclose (pDesfFile); 

The third parameter to fwrite is sizeof(buffer) which is 4 bytes (a pointer). You need to pass in the number of bytes to write instead (lSize).

Update: It also looks like you're missing the flag indicating the file should be Read/Write: _O_RDWR

This is working for me...

   std::string szdes = "C:\\temp\\test_des.txt"; 
   FILE* pDesfFile; 
   int iFileId2;
   err = _sopen_s(&iFileId2, szdes.c_str(), _O_CREAT|_O_BINARY|_O_RDWR, _SH_DENYNO, _S_IREAD | _S_IWRITE); 
   if (iFileId2 >= 0)  
      pDesfFile = _fdopen(iFileId2, "w+"); 

   size_t f = fwrite (buffer , 1, lSize, pDesfFile ); 
   fclose (pDesfFile); 
给我一枪 2024-12-09 14:49:53

由于找不到_sopen的信息,只能查看man open。它报告:

int open(const char *pathname, int flags);
int open(const char *pathname, int flags, mode_t mode);

您的呼叫 _sopen(szdes.c_str(),_O_CREAT,_SH_DENYNO,_S_IREAD | _S_IWRITE); 与其中任何一个都不匹配,您似乎有标志和“某些东西”和模式/什么是 SH_DENY ?

man _sopen 的结果是什么?

最后,在 fclose 文件指针后,不应该从 _sopen 关闭文件描述符吗?

顺便说一句,您的最后几行应该如下所示:

if (iFileId2 >= 0) 
{
  pDesfFile = fdopen(iFileId2, "w+");
  size_t f = fwrite (buffer , 1, sizeof(buffer),pDesfFile ); //<-- the f returns me 4
  fclose (pDesfFile);
}

因为您当前正在写入文件,无论 O_CREAT 后的 fdopen 是否成功。您也在顶部执行相同的操作,无论 RDONLY 文件的 fdopen 是否成功,您都会处理读取(和写入):(

Since I can't find info about _sopen, I can only look at man open. It reports:

int open(const char *pathname, int flags);
int open(const char *pathname, int flags, mode_t mode);

Your call _sopen(szdes.c_str(),_O_CREAT,_SH_DENYNO,_S_IREAD | _S_IWRITE); doesn't match either one of those, you seem to have flags and 'something' and modes / what is SH_DENY?

What is the result of man _sopen?

Finally, shouldn't you close the file descriptor from _sopen after you fclose the file pointer?

Your final lines should look like this, btw :

if (iFileId2 >= 0) 
{
  pDesfFile = fdopen(iFileId2, "w+");
  size_t f = fwrite (buffer , 1, sizeof(buffer),pDesfFile ); //<-- the f returns me 4
  fclose (pDesfFile);
}

Since you currently write the file regardless of whether or not the fdopen after the O_CREAT succeeded. You also do the same thing at the top, you process the read (and the write) regardless of the success of the fdopen of the RDONLY file :(

碍人泪离人颜 2024-12-09 14:49:53

您正在使用 C 和 C++ 的混合体。这很令人困惑。
sizeof 运算符不会执行您期望的操作。

You are using a mixture of C and C++. That is confusing.
The sizeof operator does not do what you expect it to do.

旧时光的容颜 2024-12-09 14:49:53

看起来像@PJL和<一个href="https://stackoverflow.com/questions/7270742/c-fwrite-dosnt-write-to-text-file-have-no-idea-why/7270808#7270808">@jschroedl 发现真正的问题,但也是一般性问题:

fwrite 指出:

fwrite 返回实际写入的完整项数,如果发生错误,该值可能小于 count。另外,如果发生错误,则无法确定文件位置指示器。

因此,如果返回值小于传递的计数,请使用 费罗尔来了解发生了什么。

ferror 例程(作为函数和宏实现)测试与流关联的文件上的读取或写入错误。如果发生错误,流的错误指示器将保持设置状态,直到流被关闭或倒回,或者直到对其调用clearerr。

Looks like @PJL and @jschroedl found the real problem, but also in general:

Documentation for fwrite states:

fwrite returns the number of full items actually written, which may be less than count if an error occurs. Also, if an error occurs, the file-position indicator cannot be determined.

So if the return value is less than the count passed, use ferror to find out what happened.

The ferror routine (implemented both as a function and as a macro) tests for a reading or writing error on the file associated with stream. If an error has occurred, the error indicator for the stream remains set until the stream is closed or rewound, or until clearerr is called against it.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文