gpt4 book ai didi

C:Read() 并使用换行符

转载 作者:行者123 更新时间:2023-11-30 17:28:14 27 4
gpt4 key购买 nike

因此,当您使用 getchar() 读取输入时,您需要使用输入的字符以及用于提交该字符的换行符。

但是,我正在尝试使用 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)

我是否误解了阅读的工作原理?我尝试在第一次读取之后添加另一次读取,以尝试使用换行符,但是,它不能解决问题。

该程序还将写入标准输出(这将是管道)。对于这种情况我需要考虑什么特别的事情吗?

最佳答案

所以,对于任何感兴趣的人,我都找到了答案。问题是我没有将指针移动到缓冲区,所以我一遍又一遍地覆盖第一个索引。

所以,这就是我让它工作的方式:

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

关于C:Read() 并使用换行符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26087963/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com