There are two common ways to read in all the data from a file:
1) Use fgets(), in a while loop. When NULL is returned, the loop should end.
2) Use fscanf(), in a while loop. When the count of objects stored is less than it should be, the loop should end.
Here's a simple example program:
Code:
#include <stdio.h>
#include <time.h>
int main(void) {
int i;
char a[7][128];
time_t start, stop;
FILE *fp=fopen("Edelweiss.txt", "r");
if(!fp) {printf("\nError: unable to open the file.\n"); return 1;}
start = time(NULL);
i=0;
while((fgets(a[i],sizeof(a[i]), fp)) != NULL) {
fputs(a[i++],stdout);
//getchar();
}
/*
//shows the use of fscanf() reading a line until it reaches a
//newline, and reading all the data in a file, while it can store at
//least one object.
while((fscanf(fp, " %[^\n]s",a[i])) > 0) {
printf("%s\n",a[i++]);
//getchar();
}
*/
fclose(fp);
stop = time(NULL);
if(stop-start > 10) {
printf("\nYour 10 seconds are up! Ending program in 4 seconds!\n");
_sleep(4);
}else {
printf("\nThat was fast! The program will end when you hit enter\n");
getchar();
}
return 0;
}
/*
In a file named "Edelweiss.txt, put this into the programs directory before you run it:
"Edelweiss, edelweiss, every morning you greet me.
Small and white, clean and bright, you look happy to meet me.
Blossom of snow may you bloom and grow, bloom and grow forever.
Edelweiss, edelweiss, bless my homeland forever.
Small and white, clean and bright, you look happy to meet me
Blossom of snow, may you bloom and grow, bloom and grow forever.
Edelweiss, edelweiss, bless my homeland forever."
*/
If you use fgets(), you have the data in a string. You still need to use sscanf() to store the numbers out of the string, into your array. If the data is STRICTLY formatted - not user entered (which will always have errors), then fscanf() is perfectly fine to store the data into the array.