HxH HxH - 2 months ago 7
C Question

If I don't know the content in the file, how should I read the content and store different parts that separated by whitespace?

Here I have a example about reading file in c. For example, if I have a file on the computer called "file" with some string "a b c". If I want to print them out, I can use the code below.

#include <stdio.h>
#include <stdlib.h>

int main()
char str1[10], str2[10], str3[10];
FILE * fp;

fp = fopen ("file", "r");

fscanf(fp, "%s %s %s", str1, str2, str3);

printf("|%s| ", str1 );
printf("|%s| ", str2 );
printf("|%s| ", str3 );


return 0;

And it will print"|a| |b| |c|".

What if I don't know the length of string in the file.
So if I have"a b c d" or "a b" in the file. How should I read the content in the file and print them out?


You could use http://man7.org/linux/man-pages/man3/getdelim.3.html that malloc the right size for you. Exemple at the end of the man