1

I have a text file "hello.txt" with some sample text. When I open the file in a hex editor, I can see \r\n characters for the newline. But when I read the file in a C program with getc() the \r somehow vanishes and I only see the \n character.

I tried to search online and on stackoverflow but with no luck.

hello.txt

Sample
File

Code:

#include <stdio.h>

int main()
{
    FILE *fp;
    fp = fopen("hello.txt", "r");

    int character = 0;

    while( (character = getc(fp)) != EOF)
    {
        printf("%.2X ", character);
    }

    return 0;
}

Output:

53 61 6D 70 6C 65 0A 46 69 6C 65

File as seen from hex editor:

53 61 6D 70 6C 65 0D 0A 46 69 6C 65

As can be seen, the 0D0A is output as only 0A when using the getc() function.

Why does getc() avoid the '\r' character ? How can I get it to return the EXACT data in a given file i.e. without any conversions for the \r\n to \n ?

4

3 に答える 3

5

Windows では、バイナリモードでファイルを開く必要があります。

fp = fopen("hello.txt", "rb");

デフォルトのテキストモードでは、DOS/Windows の行末\r\nが 1 文字に変換されます。

于 2013-03-20T15:47:36.777 に答える
2

ファイルをテキストモードfp = fopen("hello.txt", "r");で開いて0x0Dいる場合、前にある0x0A文字は無視されます。

于 2013-03-20T15:47:28.930 に答える
2

試してみてくださいfp = fopen("hello.txt", "rb");-'b'オープンモードで、ファイルは「テストモード」で開かれ、(プラットフォームに応じて)行末が単純に変換/正規化されます\n

于 2013-03-20T15:47:50.207 に答える