Reputation: 761
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:
Repeat until reaching EOF
//Code for reading a file
int c;
while((c = getc(f))!= EOF) {
//Build a string here consisting of characters from c, until reaching a new line.
/*
if(c == '\n') { //Indicates a new line
//Insert the line you have into the linked list: insert(myLinkedList, line);
}
*/
}
fclose(f); //Close the file
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
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
Reputation: 399861
Replace your character-by-character reading by something more high-level.
fgets()
, but that requires you to specify a static limit for the line's length.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