Search code examples
cconsolefgetscarriage-returnlinefeed

C - fgets skips CR character


I have a c code, simply reads a line from a txt file. The file has only one line which is as below:

Content of txt file

The code snippet to read this line is:

int** readFile(char* filename){

    int col=0, row =0;
    int i=0;
    int* numList[2048];

    for(int i = 0; i<2048; i++)
        numList[i] = (int*) malloc(6*sizeof(int));

    if(NULL == numList){

        printf("Memory error!");

    }

    char * token = NULL;

    char currentLine[25] = {'\0'};

    FILE* file = fopen(filename, "r");

    if(NULL != file){

        printf("File is opened successfully\n");

        if( NULL != fgets (currentLine, 60, file) ) 
        {
            int i = 0;
            while (NULL != currentLine[i]){

                printf("%d ", currentLine[i]);
                i++;
            }
        }
    }
    else
    {
        printf("File I/O Error");
        return NULL;
    }

    fclose(file);

    return numList;
}

When this code runs, I get the following output:

Output of program

I observed something suspicious, which is, as you can see in the first screenshot (Content of txt file), Notepad++ shows CR LF at the end of the line. But in the output, I see 10 as the last character which is LF.

Probably I am missing a very primitive point but, I couldn't understand why CR character is not there.

Needless to say, platform is windows and this is a console program.

Thanks&Regards.


Solution

  • You're opening the file in text mode. This mode ensures you can handle text files the same on any platform.

    C specifies '\n' as the end of line. In Windows, the end of line is the sequence "\r\n". C (in this case, the standard library implementing stdio) will automatically translate this for you. Reading from a file on Windows in text mode will give you just \n for \r\n.

    If you want to see exactly the byte contents of the file, you have to open it in binary mode instead:

    FILE* file = fopen(filename, "rb");