0

我在 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?

4

3 回答 3

2
t_rawImageFile.open(rawImageFileName, std::ifstream::in || std::ios::binary );

...不以二进制模式打开文件。由于||是惰性或运算符并且std::ifstream::in不为零,因此整个表达式具有值1

t_rawImageFile.open(rawImageFileName, std::ifstream::in | std::ios::binary );

...肯定会工作得更好。

于 2013-05-31T13:32:18.387 回答
1

更改此行:

t_rawImageFile.open(rawImageFileName,std::ifstream::in || std::ios::binary );

进入这个:

t_rawImageFile.open(rawImageFileName,std::ifstream::in | std::ios::binary );
于 2013-05-31T13:32:26.780 回答
1

您没有显示打开文件的部分,但我很确定缺少它ios::binary以确保 C 运行时代码不会将 CTRL-Z(或 CTRL-D)解释为文件结尾。

于 2013-05-31T11:48:14.903 回答