簡體   English   中英

使用讀寫系統調用時是否需要使用while循環?

[英]Is it necessary to use a while loop when using the read and write system calls?

我正在練習讀寫系統調用,下面的代碼在 while 循環和沒有它們的情況下都可以正常工作。 你能告訴我這里的while循環有什么用嗎,是否有必要在使用讀寫系統調用時添加它。 我是初學者。 謝謝。

#include <unistd.h>
#define BUF_SIZE 256
int main(int argc, char *argv[])
{
    char buf[BUF_SIZE];    
    ssize_t rlen;
    int i; 
    char from;
    char to;
    from = 'e';
    to = 'a';

    while (1) {
        rlen = read(0, buf, sizeof(buf));
        if (rlen == 0)
               return 0;

        for (i = 0; i < rlen; i++) {
               if (buf[i] == from)
                      buf[i] = to;
        }
    write(1, buf, rlen);
   }
return 0;
}


您通常需要在readwrite中使用while循環(或一般的某種循環),因為正如您應該從手冊頁( man 2 read )中知道的那樣:

 RETURN VALUE On success, the number of bytes read is returned (zero indicates end of file), and the file position is advanced by this number. It is not an error if this number is smaller than the number of bytes requested; this may happen for example because fewer bytes are actually available right now (maybe because we were close to end-of- file, or because we are reading from a pipe, or from a terminal), or because read() was interrupted by a signal. See also NOTES.

因此,如果您想讀取超過 1 個字節,則需要在循環中執行此操作,因為read總是可以處理少於請求的數量。

同樣, write也可以處理小於請求的大小(參見man 2 write ):

 RETURN VALUE On success, the number of bytes written is returned (zero indicates nothing was written). It is not an error if this number is smaller than the number of bytes requested; this may happen for example because the disk device was filled. See also NOTES. On error, -1 is returned, and errno is set appropriately.

這里唯一的區別是,當write返回0時,它不是錯誤或文件結束指示符,您應該重試寫入。

您的代碼幾乎是正確的,因為它使用循環來繼續讀取,直到沒有更多字節要讀取(當read返回0時),但是有兩個問題:

  1. 您應該在read后檢查錯誤( rlen < 0 )。
  2. 當您使用write時,您還應該在那里添加一個循環,因為正如我剛才所說,即使write處理的字節數也可能少於請求的字節數。

您的代碼的正確版本是:

#include <stdio.h>
#include <unistd.h>

#define BUF_SIZE 256

int main(int argc, char *argv[])
{
    char buf[BUF_SIZE];
    ssize_t rlen, wlen, written;
    char from, to;
    int i;

    from = 'e';
    to = 'a';

    while (1) {
        rlen = read(0, buf, sizeof(buf));

        if (rlen < 0) {
            perror("read failed");
            return 1;
        } else if (rlen == 0) {
            return 0;
        }

        for (i = 0; i < rlen; i++) {
            if (buf[i] == from)
                buf[i] = to;
        }

        for (written = 0; written < rlen; written += wlen) {
            wlen = write(1, buf + written, rlen - written);

            if (wlen < 0) {
                perror("write failed");
                return 1;
            }
        }
    }

    return 0;
}

暫無
暫無

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

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