2014-09-28 64 views
0

因此,當您使用getchar()讀取輸入時,需要使用輸入的字符以及用於提交字符的換行符。C:讀取()並消耗換行符

但是,我試圖使用read()將輸入讀入緩衝區。該程序可能是從鍵盤或從輸入文件讀取。當我在我的程序中輸入一個字符時,它會讀入字符和換行符,但是輸入超出第一個字符的任何內容都不會讀入緩衝區。

#include <stdlib.h> 
#include <sys/types.h> 
#include <unistd.h> 
#include <stdio.h> 

    int main (int argc, char *argv[]) 
    { 

     //Success/failure of read 
     int read_status = 1; 
     //Success/failure of write 
     int write_status = 1; 
     //Buffer for reads/writes 
     char buffer[BUFSIZ] = {0}; 
     int charsRead; 

     for(charsRead = 0; charsRead < BUFSIZ && read_status > 0; charsRead++) 
     { 
      fprintf(stderr, "Ready to read.\n"); 
      read_status = read(0, buffer, 2); 

      fprintf(stderr, "First status: %i.\n", read_status); 

      fprintf(stderr, "Read a : "); 
      if(buffer[charsRead] == '\n') 
      { 
       fprintf(stderr, "newline\n"); 
      } 
      else if(buffer[charsRead] == ' ') 
      { 
       fprintf(stderr, "space\n"); 
      } 
      else 
      { 
       fprintf(stderr, "%c\n", buffer[charsRead]); 
      } 
     } 

     fprintf(stderr, "Printing read in chars: \n"); 
     for(int i = 0; i < charsRead; i++) 
     { 
      if(buffer[i] == '\n') 
      { 
       fprintf(stderr, "newline\n"); 
      } 
      else if(buffer[i] == ' ') 
      { 
       fprintf(stderr, "space\n"); 
      } 
      else 
      { 
       fprintf(stderr, "%c\n", buffer[i]); 
      } 
     } 
    } 

所以,當我運行它,它會產生這樣的輸出:

Ready to read. 
a 
First status: 2. 
Read a : a 
Ready to read. 
b 
First status: 2. 
Read a : newline 
Ready to read. 
a 
First status: 2. 
Read a : 
Ready to read. 
b 
First status: 2. 
Read a : 
Ready to read. 
g 
First status: 2. 
Read a : 
Ready to read. 
e 
First status: 2. 
Read a : 
Ready to read. 
First status: 0. 
Read a : 
Printing read in chars: 
e 
newline 
(blank) 
(blank) 
(blank) 
(blank) 
(blank) 

我誤解怎麼看的作品?我嘗試在嘗試使用換行符後添加另一個讀取,但它不能解決問題。

該程序也將寫入標準輸出(這將是管道)。我需要爲這種情況做出特殊考慮嗎?

回答

0

因此,對於任何有興趣的人,我都想出了答案。問題是我沒有將指針移動到緩衝區,所以我一遍又一遍地覆蓋第一個索引。

所以,這是我得到了它的工作:

for(bytesRead = 0; bytesRead < BUFSIZ && read_status > 0; bytesRead++) 
{ 
    read_status = read(0, buffer + bytesRead, 1); 
}