gpt4 book ai didi

c - 使用系统调用在 C 中读取文件

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

我尝试了网站上的几个解决方案答案,但无法理解这段代码出了什么问题。

我只是想读取文件 data.txt 并打印它。该文件仅包含 12 个字符“abcd1234efgh”。

fd 结果为正,但执行读取时“br”为 0。如果有人对此有一些线索,请帮忙

#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
int main(int args,char* vargs[])
{
int fd = 0;
fd = open("data.txt",O_RDONLY);
if(fd<=0)
printf("Invalid file name");
else{
off_t fs =lseek(fd, (off_t) 0, SEEK_END);
char buf[10];
off_t br = read(fd,buf,10);
printf("%s",buf);
}
return 0;
}

最佳答案

lseek(fd, 0, SEEK_END);

此文件指针设置在文件末尾后,任何进一步的读取都不会成功。只需注释掉此说明,或根据您的需要对其进行更改。

关于c - 使用系统调用在 C 中读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46042202/

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