【问题标题】:Getting weird output reading from stdin从标准输入读取奇怪的输出
【发布时间】:2016-10-02 19:59:16
【问题描述】:

所以我想要做的是重复从键盘输入到标准输出。它必须使用读/写

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define BUFFSIZE 1024
int  main() {
    char buffer[BUFFSIZE];
    while (1)
       if (read(0, buffer,  sizeof(buffer))) 
             write(1, buffer, sizeof(buffer)); 
         return 0;
}

如果我输入“你好”,它会创建一个带有一堆奇怪符号和字母的新行,而在另一个新行上它会说“你好”

【问题讨论】:

  • write 将写入由第三个参数 (sizeof(buffer)) 指定的所有字节。缓冲区不一定是满的,所以您需要使用read 的返回值来确定要写入的字节数。

标签: c linux unix


【解决方案1】:

您应该保存read() 的返回值并只写入read() 真正读取的数量。

你的代码也太混乱了,没有多大意义,你的while循环应该有一个条件,并且在这样的程序中天生就有一个,

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

#define BUFFSIZE 1024
int  
main(void) 
{
    char buffer[BUFFSIZE];
    ssize_t length;
    while ((length = read(STDIN_FILENO, buffer,  sizeof(buffer))) > 0)
        write(STDOUT_FILENO, buffer, length); 
    return 0;
}

【讨论】:

  • 谢谢。快速提问为什么你使用STD_INFILENO 而不是 0?
  • 它是STDIN_FILENO,因为它是一个扩展为stdin文件号或0的宏,但使用宏使代码更具可读性。
猜你喜欢
  • 2014-03-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-01
相关资源
最近更新 更多