简体   繁体   English

C中的程序,读写

[英]Program in C, Read and Write

This is a simple program to read the the text in secret.in and write it in secret.out but I have a question.这是一个简单的程序,可以读取secret.in中的文本并将其写入secret.out ,但我有一个问题。 I need to know what exactly the purpose from the line 20 to 24 ?我需要知道从第20行到第24行的确切目的是什么? I tried to write more than 128 letters and numbers but it didn't show up to me Characters found, c= Can someone tell me why?我尝试写超过 128 个字母和数字,但没有显示出来找到的字符,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);
}

The read function returns the number of bytes read.读取 function 返回读取的字节数。 So for more than 128 characters your call to the read function will return a value of 128, then the next time the while loop is evaluated the value of nread will be 128 which will not equal N_BUFFER so the loop will terminate.因此,对于超过 128 个字符,您对 read function 的调用将返回值 128,然后在下一次评估 while 循环时, nread的值将是 128,它不等于N_BUFFER ,因此循环将终止。

It may be more beneficial to check that that nread is greater than 0 (read will return a value of 0 for end of file).检查nread是否大于 0 可能更有益(read 将返回值 0 表示文件结束)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM