-2

I wrote this program to read a paragraph written in a file in a text file and copy it to another file. The program worked ok but when I open the copy file it had a garbage character in the end. I attach my source code below. I keep having the "ÿ" character at EOF. Can anyone help me with this?

    void main()
{
    FILE *fp;
    char ch = NULL;
    fp = fopen("vanban.txt", "r");
    if (fp != NULL)
    {
        printf("Mo File thanh cong!\n");
        printf("Doc File thanh cong!\n");
        char ch = NULL;
        FILE *fp1;
        fp1 = fopen("vanban1.txt", "w");
        do
        {
            if (ch <= 255 && ch >= 0)
            {
                ch = fgetc(fp);
                fputc(ch, fp1);
            }
        } while (ch != EOF);
        fclose(fp1);
    }
    else
    {
        printf("FIle khong mo duoc hoac khong ton tai.\n");
    }
    fclose(fp);
  • Read it out loud. Check a character is valid. If it is read another character and write it to file. See the problem? – John3136 Jun 13 '18 at 04:26
  • Quick quiz: Is `char` signed or unsigned? What values could `ch` take on that you need to test for? What values are invalid that you want to exclude? Could this code take the form of a `switch` statement? – tadman Jun 13 '18 at 04:29

1 Answers1

1

The statement

char ch = NULL;

is wrong as ch is of char type and NULL is not char type it's of (void*)0 type.

Also fgetc() returns int not char, check the manual page of fgetc(). It says

fgetc() reads the next character from streamand returns it as an unsigned char cast to an int, or EOF on end of file or error.

For e.g

int ch = 0;

while( (ch = fgetc(fp)) != EOF) {

    if (ch <= 255 && ch >= 0) /* what you are checking here ? Check whether it's really required */

           fputc(ch, fp1);

}
Achal
  • 11,821
  • 2
  • 15
  • 37