简体   繁体   中英

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. I need to know what exactly the purpose from the line 20 to 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?

#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. 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.

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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