【发布时间】:2021-08-04 00:40:29
【问题描述】:
我做了一个示例项目来将文件读入缓冲区。 当我使用 tellg() 函数时,它给我的值比 read 函数实际上是从文件中读取的。我认为有一个错误。
这是我的代码:
编辑:
void read_file (const char* name, int *size , char*& buffer)
{
ifstream file;
file.open(name,ios::in|ios::binary);
*size = 0;
if (file.is_open())
{
// get length of file
file.seekg(0,std::ios_base::end);
int length = *size = file.tellg();
file.seekg(0,std::ios_base::beg);
// allocate buffer in size of file
buffer = new char[length];
// read
file.read(buffer,length);
cout << file.gcount() << endl;
}
file.close();
}
主要:
void main()
{
int size = 0;
char* buffer = NULL;
read_file("File.txt",&size,buffer);
for (int i = 0; i < size; i++)
cout << buffer[i];
cout << endl;
}
【问题讨论】:
-
tellg() 返回 -1 吗?您是否尝试过以字符模式打开文件?
-
tellg() 返回一个更大的数字。例如,当我调试时,我看到 i 等于 60,然后 while 循环结束(意味着我们到达了 eof)但tellg 返回 65..
-
^以文本模式打开文件而不是 ios::binary?
-
^我不知道。只是想帮忙。顺便说一句,差异一致。增加文件大小,仍然tellg() = file.gcount() + 5??如果是这样,可能 tellg() 也考虑了文件 EOF 字符,而 file.gcount() 没有..