I have a text file:
ho hello blah hi dsdf hihi hiho hih bleh
The following is the code I'd use to read it.
#include <stdio.h>
int main()
{
char string1[11];
char string2[11];
char string3[11];
char string4[11];
char string5[11];
char string6[11];
char string7[11];
char string8[11];
char string9[11];
FILE * fileReader = fopen("text.txt", "r");
if(fileReader)
{
fscanf(fileReader, "%10s %10s %10s %10s %10s %10s %10s %10s %10s", string1, string2, string3, string4, string5, string6, string7, string8, string9);
printf("Found: %s %s %s %s %s %s %s %s %s\n", string1, string2, string3, string4, string5, string6, string7, string8, string9);
fclose(fileReader);
}
else
{
puts("Error opening filestream!");
}
return 0;
}
FILE *, aka streams are used for input/output in C. scanf() uses the default input stream (stdin) and so cannot be used for reading files. fscanf() allows you to specify the filestream as a parameter.
Also, using %10s prevents fscanf() from reading more than ten characters for each string. Without %10s, scanf() could cause your program to have a buffer overflow. This is basically when it reads more data than the char [] variables can hold, corrupting program memory.
if(fileReader) checks to see if fileReader was successfully opened (non-zero values = true, 0 (aka NULL) = false). I could have done it as if(fileReader != NULL), but it's the same effect.
Also, you don't use the & operator when dealing with arrays. Arrays deteriorate into pointers when passed to functions like scanf(), so by using &, you're passing scanf() the address of the pointer, which isn't what you want.
This is what I get when I compile the above code(the text file used is saved as "text.txt"):
sky@sky-Lenovo-3000-N500:~$ gcc stringReader.c -o string && ./string
Found: ho hello blah hi dsdf hihi hiho hih bleh