1

I have a FILE* object from which I want to read line by line. The most common approach however is to pass a directory to ifstream and use getline(ifstream, line) in a while loop to read line by line.

However I do not have a directory. I have to work with FILE*. Is there a getline() that accepts a FILE* as parameter? or, in general is there another way in c++ to read lines with FILE*

C read file line by line does not work for me since i'm not on linux.

I was also thinking if an ifstream can accept a FILE instead of a directory but I am not sure about this. can anyone confirm?

bcsta
  • 1,963
  • 3
  • 22
  • 61

1 Answers1

2
std::vector<std::string> getFileAsLines(FILE *file) {
  std::vector<std::string> out;
  int currentIn = fgetc(file);
  std::string currentLine;

  while(currentIn != EOF) {
    if (currentIn == '\n') {
      out.push_back(currentLine);
      currentLine = std::string();
    } else {
      currentLine += (char)currentIn;
    }

    currrentIn = fgetc(file);
  }
  out.Push_back(currentLine);
  return out;
}

Didnt test it, but the idea should go through

Narase
  • 490
  • 2
  • 12
  • In your while condition it should be `&&` or `and` not `AND` – john Jun 13 '19 at 07:53
  • @Narase so as a termination, while(line = getNextLine(File*file) != NULL) should work right? since 'out' is initially empty – bcsta Jun 13 '19 at 08:07
  • No, an empty string is not NULL since its not a pointer. Looks like youre coming from Java/C#. I edited the function so it returns the whole file as list of lines – Narase Jun 13 '19 at 08:23