Invalid loop in c

I use the code below to read char from a file and replace it with another, but I have error.loop at the end of the file.

What's wrong?

I tested this code on linux (netbeans IDE) and it was right and worked beautifully, but when I tried to use VS 2008 on Windows, I found a loop without end.

//address = test.txt FILE *fp; fp=fopen(address,"r+"); if(fp == 0) { printf("can not find!!"); } else { char w = '0'; /// EDIT : int w; while(1) { if((w = fgetc(fp)) != EOF) { if((w = fgetc(fp)) != EOF) { fseek(fp,-2,SEEK_CUR); fprintf(fp,"0"); } } else { break; } } } fclose(fp); 
+4
source share
2 answers

The fopen documentation on cplusplus.com says:

For modes in which letters (or additions) are allowed (those that contain the β€œ+” sign), the stream must be flushed (fflush) or (fseek, fsetpos, rewind) between the read operation followed by a write or write operation, and then read operations.

We can add a fflush call after fprintf to satisfy this requirement.

Here is my working code. It creates a file called example.txt and after the program exits, the contents of this file will be 000000000000n .

 #include <stdio.h> int main(int argc, char **argv) { FILE * fp; int w; fp = fopen("example.txt","w"); fprintf(fp, "David Grayson"); fclose(fp); fp = fopen("example.txt","r+"); while(1) { if((w = fgetc(fp)) != EOF) { if((w = fgetc(fp)) != EOF) { fseek(fp,-2,SEEK_CUR); fprintf(fp,"0"); fflush(fp); // Necessary! } } else { break; } } fclose(fp); } 

This has been tested with MinGW on Windows.

+3
source

You save the result of fgetc in char instead of int.

 char w = '0'; /* Wrong, should be int. */ 

By the way, this problem is mentioned in frequently asked questions>.

If the char type is unsigned , the actual EOF value will be truncated (by lowering its bits, it probably results in 255 or 0xff) and EOF will not be recognized , which leads to input .

EDIT

Repeating his question, he is very suspicious of how you look for two characters and write one character. This can lead to an endless loop.

EDIT2

You (probably) want something like this (untested):

 while ((w = getc(fp)) != EOF) { fseek(fp, -1, SEEK_CUR); fprintf(fp, "0"); fflush(fp); /* Apparently necessary, see the answer of David Grayson. */ } 
+6
source

All Articles