我正在尝试将整个输入文件读入字符串。现在我有:
bool DynString::readLine(std::istream& in)
{
if(in.eof())
{
*this = DynString(); // Default string value.
return(false);
}
char s[1001];
in.getline(s, 1001);
// Delete old string-value and create new pBuff string with copy of s
delete [] pBuff;
pBuff = new char[strlen(s) + 1];
DynString pBuff(s);
return(true);
}
bool DynString::readFile(const char filename[])
{
std::ifstream in(filename);
if(! in.is_open() )
{
*this = DynString(); // Default string value.
return(false);
}
// Delete old string-value and
// Read the file-contents into a new pBuff string
delete [] pBuff;
DynString tempString;
return(true);
}
其中pBuff是名为DynString的动态字符串对象
我认为我要做的是创建一个临时的DynString对象并将其作为temp,然后使用readLine方法将临时字符串分配给文本文件的一行。一旦完成,我将删除旧的字符串数组“pBuff”,然后将temp复制到新的pBuff数组。
这是否需要使用concatonate函数,我只是将temp数组中的元素添加到现有的pBuff中?
很抱歉,如果这有点令人困惑,它在头文件中有其他方法,但包含它太多了。
答案 0 :(得分:0)
为什么不像以下那样简单,或者你必须使用你的DynString类?
static std::string readFile(const std::string& sFile)
{
// open file with appropriate flags
std::ifstream in1(sFile.c_str(), std::ios_base::in | std::ios_base::binary);
if (in1.is_open())
{
// get length of file:
in1.seekg (0, std::ios::end);
std::streamoff length = in1.tellg();
in1.seekg (0, std::ios::beg);
// Just in case
assert(length < UINT32_MAX);
unsigned uiSize = static_cast<unsigned>(length);
char* szBuffer = new char[uiSize];
// read data as a block:
in1.read (szBuffer, length);
in1.close();
std::string sFileContent(szBuffer, uiSize);
delete[] szBuffer;
return sFileContent;
}
else
{
// handle error
}
}