Reputation: 117
I have a text file. I am writing a program to read from the file using fgetc and put in a two dimensional buffer.
After printing the contents of file, it's printing some junk until end of buffer despite having put the check for EOF and ERROR as shown below. How can I get it done?
unsigned char ch;
while(ch=fgetc(fp))
{
if(ch== EOF || ch==NULL)
break;
//OTHER INSTRUCTIONS
}
Thanks :)
Upvotes: 1
Views: 1373
Reputation: 1
Reading from the open file (till the end of file) should be done like this:
int ch;
while((ch = fgetc(fp)) != EOF) {
/* your code */
}
Upvotes: 0
Reputation: 5092
EOF
is an Integer with the value -1
.
When you do ch=fgetc(fp)
in the while loop, you read into an unsigned char
, that can by definition not be signed, so it can't be equal to -1
.
A solution could be to read into an integer and to cast it after having checked for EOF
.
int ch;
while(ch=fgetc(fp))
{
if(ch == EOF)
break;
//OTHER INSTRUCTIONS
}
Refer to this for a sample of how it should be implemented.
Upvotes: 3
Reputation: 2219
Your program has some errors.Use the following program,it is correct program to print all the data of any file:
#include<stdio.h>
#include<conio.h>
main()
{
FILE *fp;
char c;
fp=fopen("filename.txt","r");
clrscr();
c=fgetc(fp);
while(c!=EOF)
{
printf("%c",c);
c=fgetc(fp);
}
getch();
}
I hope that it will help you
Upvotes: -1