Add example for reading file into linked list and return the output back

This commit is contained in:
Sambo Chea 2020-08-02 12:07:05 +07:00
parent 2c10067d3e
commit 501babfbf7
3 changed files with 51 additions and 0 deletions

4
data/test.txt Normal file
View File

@ -0,0 +1,4 @@
hey, how are you?
i'm fine. thank you!
then what you think?
nothing!

BIN
test Executable file

Binary file not shown.

47
tests/readFileFromText.c Normal file
View File

@ -0,0 +1,47 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct list
{
char *text;
struct list *next;
};
typedef struct list LIST;
int main(void)
{
FILE *file;
char line[128];
LIST *current, *head;
head = current = NULL;
file = fopen("./data/test.txt", "r");
while (fgets(line, sizeof(line), file))
{
LIST *node = malloc(sizeof(LIST));
node->text = strdup(line);
node->next = NULL;
if (head == NULL)
{
current = head = node;
}
else
{
current = current->next = node;
}
}
// close the file
fclose(file);
for (current = head; current; current = current->next)
{
printf("%s", current->text);
}
return 0;
}