首页 > 连续读取文件时,第一个文件读取没问题,但是在第二个文件末尾读到了乱码。

连续读取文件时,第一个文件读取没问题,但是在第二个文件末尾读到了乱码。

文件读取函数:

char* readBytesFile(char* path) {
    FILE* file = NULL; 
    file = fopen(path, "rb");
    fseek(file, 0, SEEK_END);
    int size = ftell(file);

    rewind(file);

    char* bytes = (char*) malloc(sizeof(char) * size);

    if (fread(bytes, size, 1, file) != 1) {
        fprintf(stderr, "ERROR::Filed to read file!\n");
        free(bytes);
        bytes = NULL;
    }
        fprintf(stderr, "\n\n%s\n%s\n\n", path, bytes);
    fflush(file);
    fclose(file);
    return bytes;
}

使用readBytesFile的函数:


GLuint loadShader(char* path) {
    char* source = readBytesFile(path); 

    int offset = strlen(path) - 5;

    GLenum glShaderType;
    if (strcmp(path + offset, ".vert") == 0) {
        glShaderType = GL_VERTEX_SHADER;
        #ifdef _INFO_TYPE_
        fprintf(stdout, "SHADER::TYPE:GL_VERTEX_SHADER\n");
        #endif
    } else if (strcmp(path + offset, ".frag") == 0) {
        glShaderType = GL_FRAGMENT_SHADER;
        #ifdef _INFO_TYPE_
        fprintf(stdout, "SHADER::TYPE:GL_FRAGMENT_SHADER\n");
        #endif
    }

    GLuint shader;
    shader = glCreateShader(glShaderType);
    glShaderSource(shader, 1, &source, NULL);

    glCompileShader(shader);

    check_shader_error(shader);

    free(source);

    return shader;
}

调用

loadShader("shader.vert");
loadShader("shader.frag");

读取到的文件内容第一个没问题。第二个末尾有一串乱码。一直解决不了。求教。


你没有对申请有内存进行初始化。也就是没有把内存memset


读取的时候多分配一个字节,读完之后在末尾置'0'

【热门文章】
【热门文章】