yulai
yulai

Reputation: 761

Reading file Line By Line in C

Preface:

This question is about reading a file, line by line, and inserting each line into a linked list.

I have already written the implementation for the linked list, and tested the insert() function manually. This works. I have also written the code for reading text from a file, and writing it out. Again, this also works.

OKAY: HERE'S MY QUESTION

How can I merge these concepts, and write a function that reads text from a file, line by line, and inserts each line as a node in the linked list?

When reading from a file, I do the following:

//Code for reading a file
int c;
while((c = getc(f))!= EOF) {
    putchar(c);  //Prints out the character
}
fclose(f);  //Close the file

The insert() function takes two parameters, one being the linked list head node, and the second one being the dataEntry ("string") to be held in that node.

void insert(node_lin *head, char *dataEntry) { ... }

Hence, since the function getc gets each character separately, and the putchar writes out each character to the screen, I imagine the code to do something along these lines:

The thing is, I already have a working read_file function, as well as a working insert() function. The thing I need help with is separating the file into lines, and inserting these.

Thanks guys!

Upvotes: 2

Views: 15943

Answers (2)

Adarsh
Adarsh

Reputation: 893

You can use fgets to read entire line from the file until new line character is encountered

fgets (buffer, 128, f);

When reading from a file, you can do the following:

//Code for reading a file
char buffer[128];                 // decide the buffer size as per your requirements.
while((fgets (buffer, 128, f))!= NULL) {
    printf (buffer);
}
fclose(f);  //Close the file

Upvotes: 3

unwind
unwind

Reputation: 399861

Replace your character-by-character reading by something more high-level.

  • The most typical choice would be fgets(), but that requires you to specify a static limit for the line's length.
  • If you have getline() you can use that, it will handle any line-length but it is POSIX, not standarc C.

Also, you should change your insert() function to accept const char * as the second argument (and remember to allocate memory inside and copy the text, of course).

Upvotes: 5

Related Questions