c++ - 连续读取文件时,第一个文件读取没问题,但是在第二个文件末尾读到了乱码。
黄舟
黄舟 2017-04-17 14:26:42
0
2
419

文件读取函数:

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");

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

黄舟
黄舟

人生最曼妙的风景,竟是内心的淡定与从容!

reply all(2)
黄舟

You have not initialized the allocated memory. That is to say, the memory memset

is not set
伊谢尔伦

Allocate one more byte when reading, and set '0' at the end after reading

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!