使用 ifstream 无法获取二进制文件的正确大小

问题描述 投票:0回答:0

在我的应用程序片段中,我需要获取二进制文件的大小(字节数)。我的函数使用 get() 方法并在该方法返回 True 时递增。

我的应用程序首先读取原始二进制文件并读取正确的文件大小。然后我在创建的 temp.bin 文件的开头插入 8 个字节。接下来,我将原始文件的内容复制到 temp.bin 文件中,在另一个功能中,我检查了 temp.bin 文件的大小,但它读取了错误的大小(字节数较少)。

我初始化流如下:

   std::ifstream FileInput;
   std::ofstream TempFileOutput;
   std::ifstream TempFileInput;
   FileInput.open(BinaryFilePath.c_str(), std::ios::in | std::ios::binary);
   TempFileOutput.open("temp.bin", std::ios::out | std::ios::binary);
   TempFileInput.open("temp.bin", std::ios::in | std::ios::binary);
   FileInput.unsetf(std::ios::skipws);
   TempFileOutput.unsetf(std::ios::skipws);
   TempFileInput.unsetf(std::ios::skipws);

获取文件大小的函数

std::streamsize get_file_size(std::ifstream &File)
{
   char byte;
   File.clear();
   File.seekg(0, File.beg);
   File.unsetf(std::ios::skipws);
   std::streamsize size = 0;
   while (File.get(byte))
   {
      size++;
   }
   File.clear();
   File.seekg(0, File.beg);
   std::cout << "get_file_size: " << std::hex << size << std::endl;
   return size;
}

原始bin文件的读取大小

get_file_size(FileInput);

temp.bin读取大小

std::streamsize read_whole_file(std::ifstream &file, char *&ReturnedBuff, int offset)
{
   std::streamsize size = get_file_size(file);
   file.seekg(offset, file.beg);
   std::cout << "SizeIn: " << std::hex << size << std::endl;

LOGS(第一个原始文件,第二个temp.bin)

get_file_size: 3d6bf
get_file_size: 3d000

使用 HxD 仔细检查二进制文件,它们已正确保存。原始文件的 HxD 大小与应用程序中计算的大小相匹配。 HxD 中 temp.bin 的大小是预期的 3d6c7,但计算出的大小是错误的。

预计得到相似的大小,temp.bin 大小应该高出文件开头插入的 8 个字节。

c++ file-io fstream
© www.soinside.com 2019 - 2024. All rights reserved.