[C++]Windows下读文件问题

static char* readShaderSource(const char* shaderFile)
{
	FILE *fp;
	fopen_s(&fp, shaderFile, "r");

    if ( fp == NULL ) { return NULL; }
    fseek(fp, 0L, SEEK_END);
    long size = ftell(fp);
    fseek(fp, 0L, SEEK_SET);
    char* buf = new char[size + 1];
    fread(buf, 1, size, fp);

    buf[size] = '\0';
    fclose(fp);
    return buf;
}

因為windows換行符實際上是\r\n兩個字節,因此最後 size 由偏移量計算出來的值會比讀入的值多,也就是數組開大了。此時把數組的最後一位置為終止符,多出來的就變成了屯屯屯屯。

posted @ 2018-03-31 21:51  zengzhaocheng  阅读(196)  评论(0编辑  收藏  举报