一次从虚拟文件中读取 4 个字节

Read from dummy file 4 bytes at a time

本文关键字:读取 字节 文件 虚拟 一次      更新时间:2023-10-16

尝试一次从文件中读取 4 个字节,但我无法确切地弄清楚如何调整 ifstream.read() 的参数以使其正常工作。

作为旁注:该文件("dummy.txt")只是通过Windows命令行"fsutil.exe"创建的虚拟文件,因此文件中没有任何实际的整数。

//Benchmark Program in C++
#include <iostream>
#include <fstream>
#include <time.h>
using namespace std;
int main() {
    clock_t t1,t2;
    t1=clock();
    int temp;
    int myint;
    ifstream fstr;
    fstream dummy("dummy.txt", ios::binary);
    while(!dummy.eof()) {
        temp = fstr.read(reinterpret_cast<char*>(&myint), sizeof(int));
    }
    cout << "Hard Drive Benchmark"
         << endl;
    t2=clock();
    float diff ((float)t2-(float)t1);
    float seconds = diff / CLOCKS_PER_SEC;
    cout << "Time Taken: " << seconds << " seconds" <<endl;
}

我收到的错误是:

C:\用户\Tai\桌面\文件基准测试.cpp||在函数 'int main()' 中:| C:\用户\Tai\桌面\文件基准测试.cpp|15| 错误:从"std::basic_istream::__istream_type {aka std::basic_istream}"到"int" [-permissive]| C:\Program Files (x86)\codeblocks\mingw\lib\gcc\mingw32\4.8.1\include\c++\bits\basic_ios.h|115|

注意:候选为:标准::basic_ios<_CharT,_Traits>::运算符 void*() 常量 [_CharT = 字符; _Traits = 标准::char_traits] | C:\Program Files (x86)\codeblocks\mingw\lib\gcc\mingw32\4.8.1\include\c++\bits\basic_ios.h|115|

注意:隐式"this"参数从"void*"到"int"的转换没有已知的转换| ||=== 构建失败:1 个错误、0 个警告(0 分钟、0 秒)===|

我会像这样编写循环:

uint32_t myint;
while(fstr.read(reinterpret_cast<char*>(&myint), sizeof(myint))) {
    // do something with myint
}
  • 在实际对象上使用 sizeof(尽量减少出错的机会)
  • 注意体系结构差异 (http://en.wikipedia.org/wiki/Endianness)
  • eof 检查很少有用。它仅在检测到错误才有用(以确定特定提取是否失败 - 因此您可以尝试其他操作 - 或者流的末尾已到达)

  • stream对象的布尔值的上下文转换旨在简化错误诊断