簡體   English   中英

C中的程序,讀寫

[英]Program in C, Read and Write

這是一個簡單的程序,可以讀取secret.in中的文本並將其寫入secret.out ,但我有一個問題。 我需要知道從第20行到第24行的確切目的是什么? 我嘗試寫超過 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);
}

讀取 function 返回讀取的字節數。 因此,對於超過 128 個字符,您對 read function 的調用將返回值 128,然后在下一次評估 while 循環時, nread的值將是 128,它不等於N_BUFFER ,因此循環將終止。

檢查nread是否大於 0 可能更有益(read 將返回值 0 表示文件結束)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM