当文件具有足够的数据c++时,无法从文件中读取足够的数据

Can not read enough data from a file when the file has enough data c++

本文关键字:数据 文件 读取 c++      更新时间:2023-10-16

我在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 );