我无法打印出我写的文件

时间:2015-11-05 03:38:53

标签: c++ file

我创建了一个在文本文件上写一些数据的函数,它工作正常。我创建了另一个函数来读取文件的所有内容,并为我打印出来!但是,由于某种原因它不起作用。有人可以帮忙吗?

这是我的功能:

void myClass::displayFile() {
  char line[LINE]; //to hold the current line

  file.open("data.txt", ios::app);

  //keep reading information from the file while the file is open and has data
  while (!file.fail() && !file.eof()) {
    int lineSize; //to loope through each line

    file.getline(line, LINE);
    lineSize = strlen(line);

    //loop through the line to print it without delimiters
    for (int i = 0; i < lineSize; ++i) {
      if (line[i] == ';') {
        cout << " || ";
      } else {
        cout << line[i];
      }
    }
  }
  file.close();
  file.clear();

  if (file.fail()) {
    cerr << "Something went wrong with the file!";
  }
}

注意:函数编译并且可以访问循环,但是行字符串为空。

这个是写作功能:

void myClass::fileWriter() {
  file.open("data.txt", ios::app);
  file << name << ";" << age << ";" << "\n";
  file.close();
  file.clear();
}

1 个答案:

答案 0 :(得分:0)

愚蠢的我,你问题的原因是从一开始就盯着我,而app开放模式就是问题所在。它是以 write 模式打开文件,这意味着你无法从中读取文件。

即使您可以从文件中读取,光标也会放在文件的末尾,无论如何都会在第一次迭代中设置eofbit标志。

如果您想从文件中读取,请使用std::ifstream,如果您未指定模式,则自动设置in模式,或者您必须明确设置{{打开时的1}}模式。