你怎么看所有输入preceding的CTRL-D顺序? [英] How do you read all input preceding the CTRL-D sequence?
问题描述
使用系统调用用C阅读
#include <unistd.h>
int main()
{
char data[128];
while(read(0, data, 128) == 0){
read = read(0, data, 128)+ read //counting the amount of chars read in
}
exit(0);
}
我想输入时按CTRL + D终止,这样,用户可以preSS输入,它就会转到新的线路。现在它没有发挥作用的方式。
I would like the input to terminate upon ctrl+d, that way a user can press enter and it will just go to the new line. Right now it is not functioning that way.
读取返回一个整数,表示它读的字节数。我怎么会停止阅读,一旦用户preSS CTRL + D,换句话说,你可以继续阅读,同时pressing进入,但如果按CTRL + D是pssed $ P $,然后回到我多少个字符只读停止。
Read returns a integer indicating the number of bytes it read. How would I stop reading once the user press ctrl + d, in other words you can continue reading while pressing enter but only stop when ctrl+d is pressed and then return how many characters I read.
推荐答案
这听起来像你需要寻找到无缓冲输入。 本网站建议禁止使用termios的功能规范(缓冲)输入。这里的东西我使用示例code它们提供写道。这将允许用户能够输入的文本,直到按下Ctrl-D信号被读取(0X40)在该点它将输出读取的字节数。
It sounds like you need to look into nonbuffered input. This site suggests disabling canonical (buffered) input using termios functions. Here's something I wrote using the sample code they provide. This will allow the user to input text until the Ctrl-D signal is read (0x40) at which point it will output the number of bytes read.
#include <unistd.h>
#include <termios.h>
void print_int(int num);
int main()
{
struct termios old_tio, new_tio;
unsigned char c;
/* get the terminal settings for stdin */
tcgetattr(STDIN_FILENO, &old_tio);
/* we want to keep the old setting to restore them a the end */
new_tio = old_tio;
/* disable canonical mode (buffered i/o) and local echo */
new_tio.c_lflag &=(~ICANON & ~ECHOCTL);
/* set the new settings immediately */
tcsetattr(STDIN_FILENO, TCSANOW, &new_tio);
char buf[128] = {0};
int curr = read(STDIN_FILENO, buf, 128);
int nbyte = curr;
while (curr && buf[0] != 0x04) {
curr = read(STDIN_FILENO, buf, 128);
nbyte += curr;
}
/* restore the former settings */
tcsetattr(STDIN_FILENO, TCSANOW, &old_tio);
write(STDOUT_FILENO, "Total bytes: ", 13);
print_int(nbyte);
write(STDOUT_FILENO, "\n", 1);
return 0;
}
void print_int(int num) {
char temp[16];
int i = 0, max;
while (num > 0) {
temp[i++] = '0'+(num % 10);
num /= 10;
}
max = i;
for (i=(max-1); i>=0; i--) {
write(STDOUT_FILENO, &temp[i], 1);
}
}
请注意,在他们的样本code,它们使用〜ECHO
,但我相信你想看到输入您键入它,所以〜ECHOCTL
将只禁用呼应控制字符(如^ D在输入的结束)。
Note that in their sample code, they use ~ECHO
, but I assume you want to see the input as you type it, so ~ECHOCTL
will only disable echoing control characters (e.g., the ^D at the end of input).
这篇关于你怎么看所有输入preceding的CTRL-D顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!