ifstream 对象的 .read() 问题 *char

ifstream Object's .read() Problems of *char

本文关键字:问题 char 对象 read ifstream      更新时间:2023-10-16

我的代码:

ifstream Reader ("commands.txt");
if(Reader.fail())
{
    error("File "commands.txt" could not be found or opened.n");
}
Reader.seekg(0, Reader.end);
int FSize = Reader.tellg();
if(FSize == 0)
{
    cout << "File "commands.txt" is empty.n";
    return 0;
}
char * ContentsHold = {};
Reader.read(ContentsHold, FSize);
Reader.close();
string Contents(ContentsHold);

这个想法是,在最后,Contents应该是一个c++字符串,它包含commands.txt中的所有内容。我得到了错误"basic_string::_S_construct null not valid"。我不知道出了什么问题。帮助

这里有什么,

char* ContentsHold = {};

声明一个指向用null常量初始化的字符的指针。这不是指向数组第一个元素的指针,您必须使用new[]语法:

char* ContentsHold = new char[FSize];

这将创建一个数组,并且ContentsHold将指向它的第一个元素。更好的方法是使用std::string并公开其第一个元素的地址:

std::string ContentsHold(FSize);
Reader.read(&ContentsHold[0], FSize);

这样你就不用担心删除新的内存了。