gpt4 book ai didi

c - 从文件读取时填充 malloc 数组

转载 作者:太空宇宙 更新时间:2023-11-04 04:12:26 31 4
gpt4 key购买 nike

// 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. 使用lseek函数将文件指针移动到文件末尾,并存储到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);
}

如果解决了请告诉我:)

关于c - 从文件读取时填充 malloc 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55696250/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com