Monday, May 11, 2009

Different ways of reading a file in C

In C there are different methods to read a file, but which is more suitable to your code is important. Here we look into different functions and see how it reads from a file.

file.txt (Input)
I am in your blogspot.

fscanf:

FILE *stream,*fopen();
stream=fopen("file.txt","r");
while(!feof(stream))
{
fscanf(stream,"%s",x);
printf("%s\n",x);
}

output:
I
am
in
your
blogspot.
blogspot.

It is clear that is taking string by string and printing on the screen. Have you notice blogspot. is printing twice. we can avoid that using memcpy command.

#include
main()
{
FILE *stream,*fopen();
char x[100];
stream=fopen("file.txt","r");
while(!feof(stream))
{
fscanf(stream,"%s",x);
printf("%s\n",x);
memcpy(x,"\0",100); // every time it clears x
}
}

Output:
I
am
in
your
blogspot.

fgets:

while(fgets(x,5, stream) != NULL)
{
printf("%s\n",x);
}

Output:
I am
 in
your
 blo
gspo
t.

Every time, fgets method takes 5 character from the stream and puts into user buffer.

fgetc:

x=fgetc(stream);
while(x!=EOF)
{
printf("%c\n",x);
x=fgetc(stream);
}

Output:
I

a
m

i
n

y
o
u
r

b
l
o
g
s
p
o
t
.

it reads character by character from file.

No comments: