0

I made a simple C code for comparing two occasions of file stream. Both are reading .txt file and writing what it read to new .dat file(binary). The question is that the result file is different depending on the location of cursor in .txt file, which means whether '\n' exists at the end of file. Left case doesn't have '\n' at the last sentence, but right case does. I think this is related with "when does program notice 'EOF'?". Please help me. enter image description here

and code is below.

#include <stdio.h>
#include <string.h>

int main(){
    FILE* src = fopen("/Users/Chois/Desktop/test.txt", "rt");
    FILE* dest = fopen("/Users/Chois/Desktop/dest.dat", "wb");

    char buff[50];
    int countOfWirte = 0;

    if(src!=NULL && dest!=NULL){
        fgets(buff, 50, src);
        while(!feof(src)){
            fwrite(buff, sizeof(char), 50, dest);
            countOfWirte++;
            fgets(buff, 50, src);
         }
    }else{
        printf("fail");
    }

    printf("fwrite work %d times\n", countOfWirte);

    fclose(src);
    fclose(dest);
}

Thanks.

Chois
  • 75
  • 1
  • 2
  • 7

1 Answers1

1

Change the while condition to

while (fgets(buff, 50, src) != NULL)

when fgets() tries to read beyond the EOF then the indicator is set, so feof() would return true after the failed read, if you instead check for the return value of fgets() which will return NULL at the end of file, you would avoid this problem.

This question is asked with some frequency and there is a good answer to it here

Also, you should not do this

fwrite(buff, sizeof(char), 50, dest);

because you don't know whether 50 chars where successfully read, instead use fread() like

size_t readBytes; 

while ((readBytes = fread(buf, 1, sizeof(buf), src)) > 0)
{
    fwrite(buf, 1, readBytes, dest);
    countOfWrite++;
}

Or if you want to read lines from the file, then fprintf() would be aproppriate

while (fgets(buf, sizeof(buf), src) != NULL)
{
    fprintf(dest, "%s", buf);
    countOfWrite++;
}

Oh, and sizeof(char) must be 1.

Community
  • 1
  • 1
Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97