【发布时间】:2022-01-21 09:11:51
【问题描述】:
这是一个读取secret.in中的文本并将其写入secret.out的简单程序 但我有一个问题。我需要知道从 20 到 24 行的具体用途是什么? 我尝试写超过 128 个字母和数字,但没有显示出来 Characters found, c= 谁能告诉我为什么?
#include <fcntl.h> // open
#include <stdio.h> // printf
#include <stdlib.h> // exit
#include <unistd.h>
#define N_BUFFER 1
int main(int argc, char *argv[]) {
char buffer[N_BUFFER], c;
int in, out;
int nread = N_BUFFER;
int i;
c = '\0';
if (argc > 1) c = argv[1][0];
in = open("secret.in", O_RDONLY);
out = open("secret.out", O_WRONLY);
while (nread == N_BUFFER) {
nread = read(in, buffer, 128);
for (i = 0; i < nread; i++) { // line 20
if (c == buffer[i] && argc > 0)
printf(" Characters found, c= %d\n", c);
} // line 24
write(out, buffer, nread);
}
close(in);
close(out);
exit(0);
}
【问题讨论】:
-
一个细节:
argc > 0在循环中是常量(第 20-24 行)。也许移动该条件以封闭循环 - 或完全删除它会使其更清晰? -
#include <fcntl.h> // open,fcntl需要O_RDONLY和O_WRONLY,include <unistd.h>需要open() -
您正在定义一个长度为 1(
N_BUFFER) 的缓冲区,但使用read函数表示您的缓冲区的长度大于或等于 128 个字节。您应该使用 N_BUFFER 更改 128。 -
对于成功读取的输入的每个字节,都会打印一次消息“Characters found...”,这等于二进制文件的第一个命令行参数的第一个字符(如果是 0,则为没有命令行参数)。