gpt4 book ai didi

调用系统调用read导致无限循环

转载 作者:行者123 更新时间:2023-11-30 14:50:52 26 4
gpt4 key购买 nike

我想制作一个非常简单的控制台应用程序来替换 Unix 命令wc -c。为此,我只需计算文件中的字节数并将其输出到控制台中。

如果我的应用程序未提供参数,它将从标准输入中读取它们(这部分我已经开始工作)。但是,如果我决定提供更多参数(有效且现有的文件名),我应该计算每个参数的字节数。

到目前为止一切顺利。这是代码

const int __OPEN_ERROR = 48;

int main(int argc, char* argv[]) {

if(argc == 1) {
char buf[3];
int count = 0, lines = 0;
while(read(0, buf, 1) != 0) {
count++;
if(buf[0] == '\n')
lines++;
}

printf("Count:%d\n", count);
printf("Lines:%d\n", lines);
}
else {
int fd, bytes = 0;
char buf[3];

for (int arg = 1; arg <= argc; arg++) {
if ((fd = open(argv[arg], O_RDONLY) < 0)) {
exit(__OPEN_ERROR);
}
while (read(fd, buf, 1) != 0) { // <-- this here leads to infinite loop.
printf("%s", buf);
bytes++;
}

printf("%d %s", bytes, argv[arg]);
}
}

exit(0);
}

请不要介意这段代码写得多么糟糕,这是我探索 C 的第一天,现在我想要的一切都是可行的解决方案。

请注意,两次读取是相同的,但后一个读取陷入无限循环,原因我无法理解。是的,打开文件成功。

最佳答案

你的循环是错误的,应该是:

char buf;
...
while (read(fd, buf, 1) == 1) {
printf("%c", buf);
bytes++;
}

read 允许您从文件描述符读取字节。给定的数字说n是一个请求,这意味着read最多读取n个字节,返回的值正是字节数有效地阅读。既然要读1个字节,那么测试是否读到1个字节。其次,当您一一读取字节(或字符)时,结果是一个字符,应该打印为。 %c 告诉 printf 将值打印为字符(%s 是打印 C 字符串)。

另一个错误是arg循环的控制,应该是:

for (int arg = 1; arg < argc; arg++) // strict test...arg from 0 to argc-1 (included) or argc (excluded)

您还必须在每个 arg 循环中将字节计数重置为 0,并关闭每个未使用的文件,因此:

for (int arg = 1; arg < argc; arg++) {
char buf;
int bytes = 0;
int fd;
if ((fd = open(argv[arg], O_RDONLY) < 0)) {
exit(__OPEN_ERROR);
}
while (read(fd, buf, 1) == 1) {
printf("%c", buf); // optionnal, counting may not print...
bytes++;
}
close(fd);
printf("%d %s", bytes, argv[arg]);
}

关于调用系统调用read导致无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48725840/

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