简体   繁体   中英

I Can't print out a file that I wrote on

I have created a function to write some data on a text file, and it works fine. I created another function to read in all the content of the file, and print it out for me! But, it is not working for some reason. Could any one help please?

This is my function:

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!";
  }
}

Note: The function compiles and the loop is accessible, but the line string is empty.

This is the writing function:

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

Silly me, the cause of your problem was staring me right in the face from the beginning, and it's the app open-mode that's the problem. It is to open the file in write mode, which means you can't read from it.

And even if you could read from the file, the cursor is placed ad the end of the file the eofbit flag would have been set inside the first iteration anyway.

If you want to read from a file, then either use std::ifstream which automatically sets the in mode if you don't specify a mode, or you have to explicitly set the in mode when opening.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM