gpt4 book ai didi

C++ ifstream在从文本文件读取时附加垃圾数据

转载 作者:搜寻专家 更新时间:2023-10-31 00:32:05 24 4
gpt4 key购买 nike

char* readFromFile(char* location)
{
int total = 0;
ifstream ifile = ifstream(location);
ifile.seekg(0, ifile.end);
total = ifile.tellg();

cout << "Total count" << total << endl;
char* file = new char[total+1];

ifile.seekg(0, ifile.beg);

ifile.read(file, total+1);

cout <<"File output" << endl<< file << "Output end"<<endl;

return file;
}

这里它正在打印文件数据,但它也附加了一些垃圾值。我该如何解决?

最佳答案

read 只是读取一些字节,它不会空终止序列。虽然 cout 需要一个空终止序列,因此它会继续打印位于数组之后的随机内存,直到遇到 0。因此您需要分配一个额外的字符,然后用一个空字符。

char* readFromFile(char* location)
{
int total = 0;
ifstream ifile = ifstream(location);
ifile.seekg(0, ifile.end);
total = ifile.tellg();

cout << "Total count" << total << endl;
char* file = new char[total+1];

ifile.seekg(0, ifile.beg);

ifile.read(file, total); //don't need the +1 here

file[total] = '\0'; //Add this

cout <<"File output" << endl<< file << "Output end"<<endl;

return file;
}

关于C++ ifstream在从文本文件读取时附加垃圾数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32263116/

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