c++ - ifstream read 和 fread 不返回相同的数据,C++

标签 c++ ifstream fread

我的问题是,在文件描述符上使用 ifstream read 和 fread 似乎不会产生相同的结果。

我打开一个文件并在 ios::binary 模式下使用 ifstream open/read 读取它的输入。然后我将这个缓冲区写到一个文件中。出1.

接下来,我打开同一个文件,使用 FILE* 文件描述符和 fread 读取它的输入。然后我将这个缓冲区写到另一个文件 out2。

当我比较 out1 和 out2 时,它们不匹配。使用 FILE* 的 out2 似乎在接近尾声时停止读取。

更令人担忧的是,两个缓冲区都与输入文件不匹配。 ifstream::read 方法似乎正在修改行尾字符,即使我将输入文件打开为 ios::binary。

fread 方法似乎返回一个小于长度 (199) 的值,尽管它读取的字符明显多于该值,正如我可以看到已读取的缓冲区。这与 seekg 命令确定的长度不匹配。

我很困惑,如有任何帮助,我们将不胜感激。附上代码。

谢谢! -朱利安

   ifstream read_file;
   read_file.open("V:\\temp\\compressiontest\\out\\test_20224-5120_256x256.jpg", ios::binary);

   read_file.seekg(0, ios::end);
   unsigned long length = read_file.tellg();
   cout << "Length: " << length << endl;
   read_file.seekg(0, ios::beg);

   unsigned char* buffer = new unsigned char[length];
   unsigned char* buf = new unsigned char[length];
   for(int i = 0; i < length; i++)
   {
      buffer[i] = 0;
      buf[i] = 0;
   }

   if(read_file.is_open())
   {
      read_file.read((char*)buffer, length);
   }
   else
   {
      cout << "not open" << endl;
   }

   read_file.close();

   FILE* read_file_1 = NULL;
   read_file_1 = fopen("V:\\temp\\compressiontest\\out\\test_20224-5120_256x256.jpg", "r");
   size_t read_len = fread(buf, 1, length, read_file_1);
   fclose(read_file_1);

   if(read_len != length)
      cout << "read len != length" << " read_len: " << read_len << " length: " << length << endl;

   int consistent = 0;
   int inconsistent = 0;
   for(int i = 0; i < length; i++)
   {
      if(buf[i] != buffer[i])
         inconsistent++;
      else
         consistent++;
   }

   cout << "inconsistent:" << inconsistent << endl;
   cout << "consistent:" << consistent << endl;

   FILE* file1;
   file1 = fopen("V:\\temp\\compressiontest\\out1.jpg", "w"); 
   fwrite((void*) buffer, 1, length, file1);
   fclose(file1);

   FILE* file2;
   file2 = fopen("V:\\temp\\compressiontest\\out2.jpg", "w"); 
   fwrite((void*) buf, 1, length, file2);
   fclose(file2);

   return 0;

最佳答案

您正在调用 fopen()读取使用 mode r 而不是 mode rb 并且写入使用 mode w 而不是 mode wb Windows(默认)意味着您在阅读和写作时都使用文本翻译,而不是二进制模式。

关于c++ - ifstream read 和 fread 不返回相同的数据,C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10323321/

相关文章:

c++ - 动态扩展指针数组

c++ - 基于 Q3DScatter 的自定义图表,QCustom3DItem 运行缓慢

c++ - ifstream 找不到文件?

c++ - 如何从文件中读取前 256 位并将它们存储在两个数组中

c++ - 为什么 volatile 会产生未定义的行为

c++ - 调用外部脚本时的奇怪行为

c++ - 二进制文件的 ifstream 与 fread

C++:strod() 和 atof() 没有按预期返回 double

c++ - 将缓冲区/指针设置为空