Reading text file into an array of lines in C

34,826

Solution 1

Breaking it down into lines means parsing the text and replacing all the EOL (by EOL I mean \n and \r) characters with 0. In this way you can actually reuse your buffer and store just the beginning of each line into a separate char * array (all by doing only 2 passes).

In this way you could do one read for the whole file size+2 parses which probably would improve performance.

Solution 2

It's possible to read the number of lines in the file (loop fgets), then create a 2-dimensional array with the first dimension being the number of lines+1. Then, just re-read the file into the array.

You'll need to define the length of the elements, though. Or, do a count for the longest line size.

Example code:

inFile = fopen(FILENAME, "r");
lineCount = 0;
while(inputError != EOF) {
    inputError = fscanf(inFile, "%s\n", word);
    lineCount++;
}
fclose(inFile);
  // Above iterates lineCount++ after the EOF to allow for an array
  // that matches the line numbers

char names[lineCount][MAX_LINE];

fopen(FILENAME, "r");
for(i = 1; i < lineCount; i++)
    fscanf(inFile, "%s", names[i]);
fclose(inFile);
Share:
34,826
Zach Conn
Author by

Zach Conn

Updated on September 13, 2020

Comments

  • Zach Conn
    Zach Conn over 3 years

    Using C I would like to read in the contents of a text file in such a way as to have when all is said and done an array of strings with the nth string representing the nth line of the text file. The lines of the file can be arbitrarily long.

    What's an elegant way of accomplishing this? I know of some neat tricks to read a text file directly into a single appropriately sized buffer, but breaking it down into lines makes it trickier (at least as far as I can tell).

    Thanks very much!