search

Home  >  Q&A  >  body text

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

文件读取函数:

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

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

黄舟黄舟2773 days ago462

reply all(2)I'll reply

  • 黄舟

    黄舟2017-04-17 14:28:42

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

    is not set

    reply
    0
  • 伊谢尔伦

    伊谢尔伦2017-04-17 14:28:42

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

    reply
    0
  • Cancelreply