为什么我在读取文件时会收到跟踪垃圾数据

时间:2014-04-18 22:08:17

标签: c file text

在阅读文件时,我会从程序中获取垃圾数据,例如 !在字符串的末尾。为什么会这样?

#include <stdio.h>
#include <stdlib.h>

char *
read_kernel(char *filename)
{   // Reads a kernel into a string in memory
    char *text = NULL;
    int length;
    FILE *file = fopen(filename, "r");

    // Return null if the kernel fails to load
    if (file == NULL)
    return NULL;

    // Find the file size
    fseek(file, 0, SEEK_END);
    length = ftell(file);
    rewind(file);

    //text = (char *) malloc(sizeof(char) * length);
    text = (char *) malloc(sizeof(char) * (length + 1));
    if (text == NULL)
        return NULL;

    // read the file's text into the text buffer
    fread(text, length, 1, file);
    fclose(file);
    file = NULL;

    text[length] = '\0'; // added zero terminator
    return text;
}

0 个答案:

没有答案