2014-09-28 55 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); 
}