-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); 
2
  • Read it out loud. Check a character is valid. If it is read another character and write it to file. See the problem? Commented Jun 13, 2018 at 4: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? Commented Jun 13, 2018 at 4:29

1 Answer 1

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); } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.