Question

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 :)

Was it helpful?

Solution

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.

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top