第37行,我正在尝试在缓冲区指针中打印数据。但是我有一个指向指针(char *缓冲区)的指针(gdhFileProp-> buffer)。由于我正在使用fread(),因此在读取文件内容时不会添加\ 0。并且由于它是指向指针的指针,因此我无法添加\ 0。

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


// Struct to hold the properties of our file
typedef struct {

    int size;
    char* name;
    char* buffer;

} FILEPROP;

FILEPROP* gdhFileProp;

// Function to parse file
int parseFile(char name[]){

    // set name
    gdhFileProp = malloc(sizeof(FILEPROP));
    gdhFileProp->name = name;

    // load file
    FILE* gdhFilePointer;
    gdhFilePointer = fopen("test.txt", "rb+");

    // get file size
    fseek(gdhFilePointer, 0, SEEK_END);
    gdhFileProp->size = ftell(gdhFilePointer);

    //get data and put it into the buffer
    fseek(gdhFilePointer, 0, SEEK_SET);
    fread(&gdhFileProp->buffer, 1, gdhFileProp->size, gdhFilePointer);
    //Print data
    printf("File properties:\nSize: %d bytes\nName: %s \nData: %s\n", gdhFileProp->size, gdhFileProp->name, &gdhFileProp->buffer);

    return 1;
}

int main()
{
    char name[] = "test.txt";
    parseFile(name);
    return 0;
}

最佳答案

您有未定义的行为:根本不会为buffer分配空间。您应该这样做,然后可以根据需要添加空终止符。或者尝试简单地使用fwrite(buffer, 1, size_read, stdout);

10-07 16:57