"rb" is different to "rt"

Today one of my colleague tried to load some text from a file and parse it. It's quit a usual task, but the usual task is unusual today. Let's see the code first.

char *data = NULL;
FILE *fp;
long size;
fp = fopen("data.txt", "rt");
if (fp)
{
    fseek(fp, 0, SEEK_END);
    size = ftell(fp);
    fseek(fp, 0, SEEK_SET);
    data = malloc(size + 1);
    fread(data, 1, size, fp);
    data[size] = '\0';
    fclose(fp);
}
if (data)
{
    /* process data */
}

The code reads whole content of the file to a C string, then parse it. It looks perfect and should run perfectly. However, the result is odd. There're some mysterious bytes at the end of the string.

After investgating the code for a few minutes, I suddently noticed he is using "rt" to open file instead of "rb", while he's using binary mode functions to process text mode file! After changing second parameter of fopen() from "rt" to "rb", the problem sloved.

Beware! If you're planning to load whole file in binary way, you must open the file in binary mode even if the file is a text file!

 

posted @ 2014-03-26 20:55  wane  阅读(249)  评论(0)    收藏  举报