C++文本文件指针问题

标签 c++ fstream

我正在编写一个函数,它应该(如果文件已经存在)将第一个数字递增一个并将函数的参数附加到文件的末尾。

例子:

  1. 追加 (4,9);
  2. 追加 (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/

相关文章:

c++ - std::getline 与 std::fstream

c++ - 尝试使用 fstream 打开文件但它不起作用

c++ - 是否可以重载 wcout << 运算符以将其替换为 WriteConsoleW?

c++ - 如何让 G++ 预处理器在宏中输出换行符?

c++ - 实现自定义 malloc() 能够跟踪 C++ 中的分配位置

c++ - 在 C++ 中获取工厂类的用户输入

c++ - 在 ubuntu 中使用 g++ 编译时,Open AL 的函数给出 undefined reference 的错误

c++ - 使用 fstream 读出 txt 文件崩溃 .exe

c++ - 从 .txt 文件中提取行,然后将单词存储到单独的数组中 | C++

c++ - 对 fstream 和指针感到困惑