我正在编写一个函数,它应该(如果文件已经存在)将第一个数字递增一个并将函数的参数附加到文件的末尾。
例子:
- 追加 (4,9);
- 追加 (5,6);
1 处的文件内容: 1\n 4\n 9
2 处的文件内容: 2\n 4\n 9\n 5\n 6
int append (int obj, int objType) {
ifstream infile;
infile.open("stuff.txt");
if (infile.fail()){
infile.close();
ofstream outfile;
outfile.open("stuff.txt");
outfile << 1 << endl << obj << endl << objType;
outfile.close();
}
else {
int length = 0;
while (!infile.eof()){
int temp;
infile >> temp;
length ++;
}
infile.close();
infile.open("stuff.txt");
int fileContents[length];
int i = 0;
while (!infile.eof()){ /*PROGRAM DOES NOT ENTER HERE*/
infile >> fileContents[i];
i ++;
}
infile.close();
ofstream outfile;
outfile.open("stuff.txt");
fileContents[0] +=1;
for (i = 0; i < length; i++){
outfile << fileContents[i] << endl ;
}
outfile << obj << endl << objType;
}
程序永远不会进入第二个 while 循环,因此内容永远不会复制到数组中,然后复制到文件中。我不确定到底是什么问题或如何解决它。任何帮助将不胜感激。 :)
最佳答案
与其以这种方式关闭和重新打开文件(我不确定此操作是否会重置您需要的文件位置!),不如使用 std::fstream::seekg()
然后将文件“倒回”到开头
infile.seekg(0, ios::beg)
关于C++文本文件指针问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1828132/