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:
- Read each character until the end of file (EOF)
- For each character, until reaching a new line ('\n'), append this to the previously read characters (building a "string)
- If reaching the end of the line, insert this "string" into the linked list
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!