-
Reading text files?
Hi,
I am trying to learn how to read from text files but have a few questions about it.
Here is my code:
Code:
#include <stdio.h>
int main()
{
char ch[9];
int i =0;
FILE *file;
file = fopen("list.txt", "r");
if(file == NULL)
{
printf("Cant open file \n \n");
}
else
{
printf("file opened \n \n");
}
while(i<15)
{
fgets(ch, 8, file);
printf("%s",ch);
i++;
}
return 0;
}
This prints a word list to screen from a text file. The text file has the following in it:
my
name
is
sam
and
i
like
c
Everything works fine but my quest is, when i type the following at the bottom of the file:
fgets(ch, 8, file);
printf("%s",ch);
fgets(ch, 8, file);
printf("%s",ch);
fgets(ch, 8, file);
printf("%s",ch);
i get the following output: my my my
How come it goes to the next line when in a loop but goes back to the start when out of a loop?
Also, there is another strange problem i'm having, if i make a variable like so: int i = 3; after where i open the file, visual studio gives me this error: Error 2 error C2143: syntax error : missing ';' before 'type'
Why do i have to make all my variables above the fopen stuff?
Thanks for any help getting my head aroung files :)
-
> Why do i have to make all my variables above the fopen stuff?
Unlike C++ (or new C99 C), normal C doesn't allow declarations and statements to be mixed.
All your variable declarations (within a block) need to be at the start.
> i get the following output: my my my
Hard to say, most likely is that you've reached the end of the file, so fgets() returns without modifying the buffer (so you print what was previously there).
> while(i<15)
while ( i < 15 && fgets(ch, 8, file) )
This is preferred since it will read either 15 lines, or until the end of file is reached.
All file reading code should have decent end of file detection.
-
> Why do i have to make all my variables above the fopen stuff?
Actually variables only need to be defined before they are initialized and before they are accessed. You can declare a variable and initialize it however as long as you are not in a loop construct.
> How come it goes to the next line when in a loop but goes back to the start when out of a loop?
Well the real answer is I don't know. I can't tell from what you said exactly what is wrong but I have a feeling it's because you ignore what fgets returns, and because of that, the fgets function doesn't know it's reached the end of the file or not, and starts from the beginning. The use of the while loop seems crucial so that the file position is actually updated.
-