读取文件直到内容结束(到达 EOF)
(尽管事实上,一次读取1个字符对系统来说是昂贵的)为什么以下函数在文件内容结束后没有停止?目前,我正在使用命令行输入
作为文件路径并使用cmd
作为终端来运行该函数。
这是代码:
int flen(int file){
int i;
char c = 0;
for(i = 0; c != EOF; i++){
read(file, &c, 1);
}
return i;
}
int main(int argc, char *argv[]){
long long len;
int fd;
if(argc != 2){
fprintf(stderr, "Usage: %s <valid_path>\n",argv[0]);
exit(EXIT_FAILURE);
}
if((fd = open(argv[1], O_RDONLY, 0)) == -1){
fprintf(stderr, "Fatal error wihile opening the file.\n");
exit(EXIT_FAILURE);
}
len = flen(fd);
printf("%d\n", len);
exit(0);
}
我认为问题可能与 for 循环条件中的 EOF
有关。但如果这是真的,我怎么知道文件何时真正结束?
(Despite the fact, reading 1 char at time is system expensive) Why the following function is not stopping after the content of a file ended? Currently I am running the function using command line inputs
for the path of the file and cmd
as teminal.
Here is the code:
int flen(int file){
int i;
char c = 0;
for(i = 0; c != EOF; i++){
read(file, &c, 1);
}
return i;
}
int main(int argc, char *argv[]){
long long len;
int fd;
if(argc != 2){
fprintf(stderr, "Usage: %s <valid_path>\n",argv[0]);
exit(EXIT_FAILURE);
}
if((fd = open(argv[1], O_RDONLY, 0)) == -1){
fprintf(stderr, "Fatal error wihile opening the file.\n");
exit(EXIT_FAILURE);
}
len = flen(fd);
printf("%d\n", len);
exit(0);
}
I think the problem could be related with EOF
in the for loop condition. But if this is true, how can I know when the file actually ends?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您应该测试
read
的返回值。另外:您的类型与
int flen()
和long long len
不匹配。You should test the return value from
read
instead.Aside: you have a type mismatch with
int flen()
andlong long len
.