Also i suggest you to look at this example (this was posted by Adak(with some modifications),hope no copyright violations are provoked )
/******************************ADAK's post********************************************** ********************/
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];
FILE *fp=fopen("Edelweiss.txt", "r");/*the name of the txt*/
if(!fp)
{printf("\nError: unable to open the file.\n"); return 1;}
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);
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.