C语言->读取文件到动态数组

C language-> Read a file to a dynamic array

所以我有一个文本文件,我希望我的函数读取该文件并将其存储在数组中。我做了一些代码,当我打印我的动态数组时,它打印出垃圾值 :< help.

char* read_message(char *filename) 
{   //gets the PATH of the txt file
    char *file_contents;
    long input_file_size;
    FILE *input_file = fopen(filename, "r");
    if(input_file == NULL)                          
    { 
         return NULL;
    }
    fseek(input_file, 0, SEEK_END);     
    input_file_size = ftell(input_file);          
    rewind(input_file);                         
    file_contents = (char*)malloc(input_file_size+1 * (sizeof(char)));    
    fread(file_contents, input_file_size, 1, input_file);   
    printf("%s",file_contents);//----Prints crap--------
    fclose(input_file);
                                                  // returns the address to the array of strings
    return file_contents;       
}    

您将文件内容读入一个字符数组。那时你还没有一个字符串,而是一个字符数组,因为末尾没有终止空字节。

当您随后使用 printf 打印此数组时,它会读取已分配内存段末尾的未初始化字节(可能还有几个不属于已分配内存的字节)。读取未初始化的字节调用 undefined behavior.

因为调用 fread 不会在读取的内容后添加终止空字节,所以您需要自己做:

fread(file_contents, input_file_size, 1, input_file);
file_contents[input_file_size] = 0;

问题就在违规 printf() 之前。

file_contents = (char*)malloc(input_file_size+1 * (sizeof(char)));    
fread(file_contents, input_file_size, 1, input_file);   
printf("%s",file_contents);//----Prints crap--------

fread() 执行二进制读取。它不会向 file_contents 添加零终止符。如果从文件读取的数据中没有值为零的字符,则 printf() 调用具有未定义的行为。

也不是 fread() 通常假定文件也被打开以进行二进制读取。您的 open() 语句不会以二进制模式打开文件。

另一个问题是:

您写道:

malloc(input_file_size + 1 * (sizeof(char)); 

乘法优先,等价于:

malloc(input_file_size + (sizeof(char)); 

你应该加上括号。