[英]Why does the following C code skip the read() system call to execute the next write() system call?
我的问题是关于Linux系统编程的,特别是关于读写API的问题。
我正在编写一个复制外壳程序。 它接受一个字符串参数,并使用空格定界符对其进行标记。 根据第一个令牌的命令,它使用其余令牌作为参数执行操作。 到目前为止,我仅针对“添加”命令实现了此功能。 该代码循环运行,直到用户为“继续”输入“ n”为止。 [Y / N]”。 但是,在第一次迭代之后,我的程序在第一次执行write()输入命令后跳过了read(),并最终显示为“ continue?”。 write()调用。 为什么它在第一个write()之后立即跳过read()调用?
int main (int argc, char *argv[]) {
int true=0;
while (true==0) {
char buff1[]="Please enter your command\n";
int count1= strlen(buff1);
write (STDOUT_FILENO, buff1, count1);
char buff2[100];
int count2=read (STDIN_FILENO, buff2, 100);
buff2[count2-1]='\0';
char *list[30]; //This creates an array of character pointers (strings)
/*
* Begin tokenization and entering tokens in list
*/
const char delim[]=" ";
char *token;
token=strtok(buff2, delim);
const char newline[]="\n";
int i=0;
while (token!= NULL) {
write (STDOUT_FILENO, newline, strlen(newline));
list[i]=token;
write (STDOUT_FILENO, list[i], strlen(list[i]));
i++;
token=strtok(NULL,delim);
}
/*
* End tokenization
*/
/*
* Begin Addition operation
*/
const char add[]="add";
if (strcmp(list[0], add)==0) {
int result=0;
for (int j=1; j<i; j++) {
result+=atoi(list[j]);
}
char sum[50];
int sumcount=sprintf(sum, "%d", result);
write (STDOUT_FILENO, newline, strlen(newline));
write (STDOUT_FILENO, sum, sumcount);
}
/*
* End Addition operation
*/
char *truefalse;
char endmessage[]="Continue: [y/n]\n";
write (STDOUT_FILENO, endmessage, strlen(endmessage));
read (STDIN_FILENO, truefalse, 1);
if (*truefalse=='n') {
true=1;
}
}
return 0;
}
您的程序具有未定义的行为。
您使用未初始化的指针指向任何有效的指针。
线
char *truefalse;
声明一个指针,但尚未初始化为指向任何有效的指针。 您继续在生产线上使用它
read (STDIN_FILENO, truefalse, 1);
代替
char *truefalse;
char endmessage[]="Continue: [y/n]\n";
write (STDOUT_FILENO, endmessage, strlen(endmessage));
read (STDIN_FILENO, truefalse, 1);
采用
char truefalse; // Make it an object instead of a pointer.
char endmessage[]="Continue: [y/n]\n";
write (STDOUT_FILENO, endmessage, strlen(endmessage));
read (STDIN_FILENO, &truefalse, 1); // Use the address of the variable.
您的代码不在第二次迭代中等待您输入任何内容的原因是,换行符仍保留在输入流中。 第二个调用只读取换行符。
阅读问题答案后,您将需要代码以跳过其余部分。
最简单的方法是使用:
int c;
while ((c = fgetc(stdin)) != EOF && c != '\n');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.