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