从文件读取时填充malloc数组

时间:2019-04-15 19:43:54

标签: c file malloc

// Trying to store the the data from a text file into an array
  char *buff(const char *path){
    int end = 0;
    char * buf;
    int f_write = open(path,O_RDONLY);
    end = lseek(f_write,0,SEEK_END);
    buf =(char*)malloc(sizeof(char*)*(end+1));
    read(f_write,buf,end+1);
    close(f_write);
    buf[end+1]= '\0';
    printf("%s\n",buf);//Prints empty line because buf has not been populated
    return buf;
 }

我试图创建一个打开文件的函数,然后使用lseek计数文件中的数据量,然后将分配给该buf数组的数据量从文件中读取并读取,然后填充buf数组。然后该函数返回buf数组。

我遇到的问题是由于某种原因我的buf数组未填充文件中的数据。因此,printf在buff函数中打印出一个空行。为什么会这样?

1 个答案:

答案 0 :(得分:0)

它会打印一个空值,因为您正在执行此操作

  1. 使用 lseek 函数将文件ponter移动到文件的末尾,并将其存储到end变量。

  2. 从文件中读取buff变量从文件末尾移动的文件指针开始

您正在尝试读取以文件结尾开始的文件,这是正常的,因为文件未通过buff返回任何内容。

尝试一下:

char *buff(const char *path){
 int end = 0; char * buf; int f_write = open(path,O_RDONLY); 
 end = lseek(f_write,0,SEEK_END);
 //now you have to move the file pointer back to the start of the file
 lseek(f_write,0,SEEK_SET);
 buf =(char*)malloc(sizeof(char*)*(end+1));
 read(f_write,buf,end+1); close(f_write);
 //EDIT
 buf[end]= '\0'; printf("%s\n",buf);
}

让我知道是否可以解决:)