2016-10-16 64 views
0

我正在使用MinGW32 4.9.3版在OpenGL4中編寫遊戲。它包含了這樣的功能:爲什麼我的字符串中隨機替換了一個字符?

void loadShaderFile(GLuint* shader, const char* filename, GLenum type){ 
    const char* path = "./res/shaders/"; // TODO: Proper path. 
    char* fullPath; 
    char* sourceCode; 
    long fileLength; 
    FILE* f; 

    fullPath = malloc(strlen(filename) * sizeof(char) + sizeof(path) + 1); 
    if(!fullPath){ 
     // TODO: Proper error handling. 
     fprintf(stderr, "Error: Could not allocate char* fullPath in void loadShaderFile()!"); 
     exit(EXIT_FAILURE); 
    } 
    strcpy(fullPath, path); 
    strcat(fullPath, filename); 

    printf("%s\n", fullPath); // Prints correct path. 
    printf("%s\n", fullPath); 

    f = fopen(fullPath, "rb"); // Does not open. 
    if(!f){ 
     // TODO: Proper error handling. 
     fprintf(stderr, "Error: Could not open %s in void loadShaderFile()!", fullPath); // Prints different string. 
     free(fullPath); 
     exit(EXIT_FAILURE); 
    } 
    fseek(f, 0, SEEK_END); 
    fileLength = ftell(f); 
    fseek(f, 0, SEEK_SET); 

    sourceCode = malloc(fileLength * sizeof(char) + 1); 
    if(!sourceCode){ 
     // TODO: Proper error handling. 
     fprintf(stderr, "Error: Could not allocate char* sourceCode in void loadShaderFile()!"); 
     fclose(f); 
     free(fullPath); 
     exit(EXIT_FAILURE); 
    } 
    fread(sourceCode, 1, fileLength, f); 
    *(sourceCode + fileLength) = '\0'; 

    *(shader) = glCreateShader(type); 
    glShaderSource(*(shader), 1, (char const * const *)&sourceCode, NULL); // Fucking pointers. 
    glCompileShader(*(shader)); 

    fclose(f); 
    free(sourceCode); 
    free(fullPath); 
} 

下面是當被稱爲loadShaderFile(&vs, "defaultVertexShader.glsl", GL_VERTEX_SHADER)輸出:

./res/shaders/defaultVertexShader.glsl 
./res/shaders/defaultVertexShader.glsl 
Error: Could not open ./res/shaders/defaultVertexShader.g$sl in void loadShaderFile()! 

正如你所看到的,FULLPATH包含正確的路徑defaultVertexShader.glsl,但只要FOPEN被稱爲,它將文件擴展名中的第一個l替換爲隨機的ASCII字符,每次運行時都會有一個不同的字符。我認爲這可能是stdio中的一個錯誤。

+2

'sizeof(path)'不是字符串的大小。 – tkausl

回答

1

你有

const char* path = ... 
fullPath = malloc(strlen(filename) * sizeof(char) + sizeof(path) + 1); 

path不是一個數組,而是一個指針,所以sizeof(path)將產生sizeof(const char *)

+0

我將'const char * path'改爲'const char path []'。像魅力一樣工作。 – AITheComputerGuy

相關問題