当文件具有足够的数据c++时,无法从文件中读取足够的数据
Can not read enough data from a file when the file has enough data c++
我在c++中有这段代码(这是在我做了一些测试,看看为什么我不能从文件中读取足够的数据之后,所以这不是最终代码,我正在寻找为什么我会得到这个结果(
size_t readSize=629312;
_rawImageFile.seekg(0,ifstream::end);
size_t s=_rawImageFile.tellg();
char *buffer=(char*) malloc(readSize);
_rawImageFile.seekg(0);
int p=_rawImageFile.tellg();
_rawImageFile.read(buffer,readSize);
size_t extracted = _rawImageFile.gcount();
cout << "s="<< s <<endl;
cout << "p="<< p <<endl;
cout << "readsize="<< readSize<<endl;
cout << "extracted="<< extracted <<endl;
cout << "eof ="<< _rawImageFile.eofbit<<endl;
cout << "fail="<< _rawImageFile.failbit <<endl;
输出如下:
s=3493940224
p=0
readsize=629312
extracted=2085
eof =1
fail=2
正如你所看到的,文件大小是3493940224,我在文件的开头(p=0(,我试图读取629312字节,但我只能读取2085?
此代码有什么问题?我确实用其他方法打开了这个文件,并从中读取了一些数据,但我使用seekg将指针移动到文件的开头。
该文件以二进制文件的形式打开。
编辑1
为了找到一个解决方案,我把所有代码都放在一个函数中,它就是:
_config=config;
ifstream t_rawImageFile;
t_rawImageFile.open(rawImageFileName,std::ifstream::in || std::ios::binary );
t_rawImageFile.seekg (0);
size_t readSize=629312;
t_rawImageFile.seekg(0,ifstream::end);
size_t s=t_rawImageFile.tellg();
char *buffer=(char*) malloc(readSize);
t_rawImageFile.seekg(0);
size_t p=t_rawImageFile.tellg();
t_rawImageFile.read(buffer,readSize);
size_t x=t_rawImageFile.tellg();
size_t extracted = t_rawImageFile.gcount();
cout << "s="<< s <<endl;
cout << "p="<< p <<endl;
cout << "x="<< x <<endl;
cout << "readsize="<< readSize<<endl;
cout << "extracted="<< extracted <<endl;
cout << "eof ="<< t_rawImageFile.eof()<<endl;
cout << "fail="<< t_rawImageFile.fail() <<endl;
结果是:
s=3493940224
p=0
x=4294967295
readsize=629312
extracted=2085
eof =1
fail=1
有趣的是,读取后,文件指针移动到一个非常大的值。由于文件大小很大,应用程序可能会失败吗?
编辑2
用另一个文件测试了相同的代码。结果如下:
s=2993007872
p=0
x=4294967295
readsize=629312
extracted=1859
eof =1
fail=1
从这次测试中我可以看出:读取后,文件指针移动到一个始终相同的大数字。它读取的数量取决于文件(!(。
编辑3
将size_t更改为fstream::pos_type后,结果如下:
s=2993007872
p=0
x=-1
readsize=629312
extracted=1859
eof =1
fail=1
为什么读取后文件位置变为-1?
t_rawImageFile.open(rawImageFileName, std::ifstream::in || std::ios::binary );
不以二进制模式打开文件。由于||
是惰性或运算符,而std::ifstream::in
不是零,因此整个表达式的值为1
。
t_rawImageFile.open(rawImageFileName, std::ifstream::in | std::ios::binary );
肯定会更好。
您没有显示打开文件的部分,但我很确定它缺少ios::binary
,以确保C运行时代码不会将CTRL-Z(或CTRL-D(解释为文件结尾。
更改此行:
t_rawImageFile.open(rawImageFileName,std::ifstream::in || std::ios::binary );
进入这个:
t_rawImageFile.open(rawImageFileName,std::ifstream::in | std::ios::binary );
相关文章:
- C++数据文件、数组和计算赋值
- 数据文件的第二行未正确读取
- 在 C++/C 中使用 CURL 发出带有数据文件的 GET HTTP 请求
- 将数据文件读入结构 C++
- 引入流时C++数据文件未正确读取?
- 如何在数据文件中查找和显示内容
- 如何处理错误"E1696命令行错误:无法在Visual Studio 2017中打开元数据文件"mscorlib.dll"?
- 尝试读取数据文件,存储在数组中并打印所有元素,但它不起作用
- 将数据文件读入对象数组时出现问题
- C :数据文件有错误:预期的无限制ID
- C 和 C++:带有错误"Expected unqualified-id"的数据文件
- 如何在C 中读取一系列数据文件
- 从数据文件中读取每2个字节,并在向量中进行比较
- 写入单个大数据文件或多个小文件:哪个更快?
- 在读取数据文件时,如何找到用户字符串输入的字谜?
- 保护外部数据文件免受未经授权的修改
- C 读取数据文件
- C 如何将数据文件读取到结构或向量以及返回结构或向量
- 具有挑战性的数据文件格式,需要将其读取为包含类对象的数组的VAR
- C 中的Google单元测试:如何编写持久数据文件