1

I want to use the push_back function to fill my vector with lines from a text file. But it overwrites all entries with the last line. Here is the source code:

  int main() {
    std::vector<char*> lines;
    FILE* file;
    file = fopen("textfile.txt", "r");
    const size_t max_line_length = 1000;
    char line[max_line_length + 1];
    while ( !feof(file)) {
      fgets(line, max_line_length, file);
      lines.push_back(line);
    }
    fclose(file);
 }

Hope somebody can help.

BenMorel
  • 34,448
  • 50
  • 182
  • 322
Homer
  • 113
  • 1
  • 2
  • 6

2 Answers2

8

You are overwriting Line, and that's actually the only thing your are storing, since you never make deep copies. Try this instead:

int main() {
    std::vector<std::string> lines; // <- change this!
    FILE* file;
    file = fopen("textfile.txt", "r");
    const size_t max_line_length = 1000;
    char line[max_line_length + 1];
    while ( !feof(file)) {
      fgets(line, max_line_length, file);
      lines.push_back(line);
    }
    fclose(file);
 }
ltjax
  • 15,837
  • 3
  • 39
  • 62
  • 3
    You'll still get an extra line in the array (probably, anyway---it's not really specified). `feof` is very much like `std::basic_ios<>::eof()`; it's only use is _after_ an input has failed. The loop should be `while ( fgets( line, max_line_length, file ) )` – James Kanze Jul 18 '12 at 17:24
1

You are pushing the same buffer (line) into every position of the vector. You'll need to either:

  1. reallocate a new char* for every line using new
  2. use strdup to copy the line buffer on every line
  3. use std::string as @milleniumbug suggested (my favorite)
Rob I
  • 5,627
  • 2
  • 21
  • 28