尝试一次读取4个字节的文件,我无法弄清楚如何调整ifstream.read()的参数以使其正常工作。
(作为旁注:文件(" dummy.txt")只是通过Windows命令行" fsutil.exe"创建的虚拟文件,因此没有' t文件中的任何实际整数。)
//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:\ Users \ Tai \ Desktop \ File-Benchmark.cpp || in function&#39; int main()&#39;: C:\用户\大\桌面\文件的Benchmark.cpp | 15 | 错误:来自&#39; std :: basic_istream :: __ istream_type {aka std :: basic_istream}&#39;的用户定义转换无效到&#39; int&#39; [-fpermissive] | c:\ program files(x86)\ codeblocks \ mingw \ lib \ gcc \ mingw32 \ 4.8.1 \ include \ c ++ \ bits \ basic_ios.h | 115 |
注意:候选者是:std :: basic_ios&lt; _CharT,_Traits&gt; :: operator void *()const [with _CharT = char; _Traits = std :: char_traits] | c:\ program files(x86)\ codeblocks \ mingw \ lib \ gcc \ mingw32 \ 4.8.1 \ include \ c ++ \ bits \ basic_ios.h | 115 |
注意:没有已知的隐式转换&#39;这个&#39;参数来自&#39; void *&#39;到&#39; int&#39; | || ===构建失败:1个错误,0个警告(0分钟,0秒(秒))=== |
答案 0 :(得分:4)
我像这样写循环:
uint32_t myint;
while(fstr.read(reinterpret_cast<char*>(&myint), sizeof(myint))) {
// do something with myint
}
eof检查很少有用。在检测到错误之后,它只是有用(以确定特定的提取是否失败 - 所以你可以尝试别的东西 - 或者达到了流的结束)
stream
对象的上下文转换为布尔值旨在简化错误诊断