c - When does program recognize EOF? -
I have created a simple code to compare the file stream twice. Both are reading the .txt file and which are read in the new .dat file (binary). The question is that the result file is different depending on the location of the cursor. The Txt file, which means that '\ n' exists at the end of the file, in the left case '\ n' is not in the last sentence, but the correct case does. I think this "when does the program notice 'EOF'?" Related to Please help me.
and the code is below.
# include & lt; Stdio.h & gt; #include & lt; String.h & gt; Int main () {FILE * src = fopen ("/ user / Chois / Desktop / test.txt", "RT"); FILE * dest = fopen ("/ user / Chois / Desktop / dest.dat", "wb"); Four fonders [50]; Int countOfWirte = 0; If (src! = Null & amp; dest! = NULL) {fgets (buff, 50, src); While ({fewr (s)} {Fwrite (buff, sarcasm), 50, dest); countOfWirte ++; fgets (buff, 50, src);}} and {printf ("unsuccessful");} Printf "Frame work% d times \ n", countOfWirte); fclose (src); fclose (destination);} thanks.
while changing condition tries to read beyond fgets ()
while (Fgets (buff, 50, src)! = Null) code> EOF is set to the indicator, so feof () fail to read After returning right, if you can check the return value of fgets () You will return the NULL at the end of the file, you will avoid this problem.
This question has been asked from some frequency and there is a good answer for this
In addition, you should not do this
framesite (buff, cephof (four), 50, lost); Because you do not know that 50 char s has been successfully read, instead use fread () such as
size_t ReadBytes; While ((readBytes = fread (buf, 1, sizeof (buf), src)) gt; 0) {fwrite (buf, 1, readBytes, dest); CountOfWrite ++; } or if you want to read the lines from the file, fprintf () will be valid
while (fgets (buff , Size (buf), src)! = Null) {fprintf (destination, "% s", buf); CountOfWrite ++; } Oh, and should be sizeof (char) 1 .
Comments
Post a Comment