gpt4 book ai didi

c++ - tellg() 函数给出错误的文件大小?

转载 作者:IT老高 更新时间:2023-10-28 12:59:05 32 4
gpt4 key购买 nike

我做了一个示例项目来将文件读入缓冲区。当我使用 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不报告文件的大小,也不报告偏移量从头开始,以字节为单位。它报告一个 token 值,它可以后来习惯找同一个地方,仅此而已。(甚至不能保证您可以将类型转换为整数类型。)

至少根据语言规范:在实践中,在 Unix 系统上,返回的值将是以字节为单位的偏移量从文件的开头开始,在 Windows 下,它将是对于在 中打开的文件,从文件开头的偏移量二进制模式。对于 Windows(和大多数非 Unix 系统),文本模式,什么之间没有直接和直接的映射 tellg返回和必须读取的字节数那个位置。在 Windows 下,您真正​​可以依靠的是该值将不小于您拥有的字节数阅读(在大多数实际情况下,不会太大,虽然最多可以增加两倍)。

如果确切知道可以读取多少字节很重要,唯一可靠的方法是阅读。你应该能够通过以下方式做到这一点:

#include <limits>

file.ignore( std::numeric_limits<std::streamsize>::max() );
std::streamsize length = file.gcount();
file.clear(); // Since ignore will have set eof.
file.seekg( 0, std::ios_base::beg );

最后,关于您的代码的另外两点:

第一行:

*buffer = new char[length];

不应该编译:你声明了 buffer成为 char* ,所以*buffer有类型 char , 并且不是指针。鉴于什么你似乎在做,你可能想声明 buffer作为一个 char** .但更好的解决方案是声明它作为 std::vector<char>&std::string& . (这样,你也不必返回大小,并且不会泄漏内存如果有异常。)

第二,最后的循环条件错误。如果你真的想一次读一个字符,

while ( file.get( buffer[i] ) ) {
++ i;
}

应该可以解决问题。更好的解决方案可能是读取数据 block :

while ( file.read( buffer + i, N ) || file.gcount() != 0 ) {
i += file.gcount();
}

甚至:

file.read( buffer, size );
size = file.gcount();

编辑:我刚刚注意到第三个错误:如果您无法打开文件,你不告诉来电者。至少,你应该设置size为 0(但某种更精确的错误处理可能更好)。

关于c++ - tellg() 函数给出错误的文件大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22984956/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com