Add example for reading file into linked list and return the output back
This commit is contained in:
parent
2c10067d3e
commit
501babfbf7
4
data/test.txt
Normal file
4
data/test.txt
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
hey, how are you?
|
||||||
|
i'm fine. thank you!
|
||||||
|
then what you think?
|
||||||
|
nothing!
|
47
tests/readFileFromText.c
Normal file
47
tests/readFileFromText.c
Normal 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;
|
||||||
|
}
|
Loading…
Reference in New Issue
Block a user