【发布时间】:2015-09-02 18:20:21
【问题描述】:
我正在尝试读取一个文件,但我意识到它会失败,因为我会尝试读取太多数据,即使该文件比我要读取的文件大得多。
文件为 120 MB,我的 ifstream 在 12967 字节处失败(即使它在 12801 处开始表现怪异。
这是说明我的问题的代码:
#include <fstream>
#include <iostream>
#include <Windows.h>
using std::ifstream;
using std::cout;
#define CORRECT_SIZE 12800
#define CORRECT_BUT_WIERD 12966
#define INCORRECT_SIZE 12967
bool check_error_bits(ifstream* f);
int main()
{
ifstream myFile("myfile.txt");
char c[CORRECT_SIZE];
char c2[CORRECT_BUT_WIERD];
char c3[INCORRECT_SIZE];
/*
* TEST A (works fine)
*/
myFile.seekg(0, std::ios_base::beg);
myFile.read(c, CORRECT_SIZE);
check_error_bits(&myFile);
cout << myFile.tellg() << std::endl; // Here, tellg() returns 12800
/*
* TEST B (works too, but acts wierd)
*/
myFile.seekg(0, std::ios_base::beg);
myFile.read(c2, CORRECT_BUT_WIERD);
check_error_bits(&myFile);
cout << myFile.tellg() << std::endl; // Here, tellg() returns 16896
/*
* TEST C (FAIL)
*/
myFile.seekg(0, std::ios_base::beg);
myFile.read(c3, INCORRECT_SIZE);
check_error_bits(&myFile);
cout << myFile.tellg() << std::endl; // Here, tellg() returns -1
system("pause");
}
bool check_error_bits(ifstream* f)
{
bool stop = false;
if (f->eof())
{
char msg[500];
strerror_s(msg, errno);
cout << "1: " << msg << std::endl;
}
if (f->fail())
{
char msg[500];
strerror_s(msg, errno);
cout << "2: " << msg << std::endl;
stop = true;
}
if (f->bad())
{
char msg[500];
strerror_s(msg, errno);
cout << "3: " << msg << std::endl;
stop = true;
}
return stop;
}
尝试读取少于 12800 字节的内容效果很好。从 128001 到 12966,它可以工作(虽然我没有检查数据是否正确),但是tellg() 返回无意义。在 12966 之后,读取完全失败。
该程序的控制台输出是:
12800
16896
1: No error
2: No error
-1
Press any key to continue . . .
任何帮助将不胜感激!
【问题讨论】:
-
我假设您使用 VC++ 作为编译器,来自
包含。你是编译成 64 位还是 32 位? -
32 位,我认为这么低的数字没关系?
-
可能不是,但它属于“很高兴知道”的类别
-
@MyUsername112358 您在调试时究竟观察到了什么?我想你做到了。
-
提示:在 myFile 构造函数中添加“ios::binary”;转储文件的 16895-16897 字节;在每次测试之间关闭和打开文件。