Difference between files written in binary and text mode

前端 未结 7 1656
南旧
南旧 2020-11-22 14:20

What translation occurs when writing to a file that was opened in text mode that does not occur in binary mode? Specifically in MS Visual C.

unsigned char bu         


        
7条回答
  •  北海茫月
    2020-11-22 15:05

    Even though this question was already answered and clearly explained, I think it would be interesting to show the main issue (translation between \n and \r\n) with a simple code example. Note that I'm not addressing the issue of the Crtl-Z character at the end of the file.

    #include 
    #include 
    
    int main() {
        FILE *f;
        char string[] = "A\nB";
        int len;
        
        len = strlen(string);
        printf("As you'd expect string has %d characters... ", len); /* prints 3*/
        f = fopen("test.txt", "w"); /* Text mode */
        fwrite(string, 1, len, f);  /* On windows "A\r\nB" is writen */
        printf ("but %ld bytes were writen to file", ftell(f)); /* prints 4 on Windows, 3 on Linux*/ 
        fclose(f);
        return 0;
    }
    

    If you execute the program on Windows, you will see the following message printed:

    As you'd expect string has 3 characters... but 4 bytes were writen to file
    

    Of course you can also open the file with a text editor like Notepad++ and see yourself the characters:

    The inverse conversion is performed on Windows when reading the file in text mode.

提交回复
热议问题