Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading text file into an array of lines in C

Tags:

arrays

c

file

text

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!

like image 326
Zach Conn Avatar asked Nov 25 '09 22:11

Zach Conn


People also ask

Which function Read file into array?

* file_get_contents — Reads entire file into a string. * file — Reads entire file into an array. * fopen — Opens file or URL.

How do you store files in an array?

In Java, we can store the content of the file into an array either by reading the file using a scanner or bufferedReader or FileReader or by using readAllLines method.

How does EOF work in C?

The End of the File (EOF) indicates the end of input. After we enter the text, if we press ctrl+Z, the text terminates i.e. it indicates the file reached end nothing to read.

What is EOF programming?

In computing, end-of-file (EOF) is a condition in a computer operating system where no more data can be read from a data source. The data source is usually called a file or stream.


2 Answers

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.

like image 178
Dan Cristoloveanu Avatar answered Sep 20 '22 06:09

Dan Cristoloveanu


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);
like image 41
Hyppy Avatar answered Sep 19 '22 06:09

Hyppy