您好Stackoverflow社区,我对此代码有疑问:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#define MAX_SIZE 50
int main()
{
char *s = malloc(sizeof(char)*MAX_SIZE);
do{
int r = read(STDIN_FILENO, s, MAX_SIZE);
if(r==-1) printf("error");
else{
write(STDERR_FILENO, s, MAX_SIZE);
}
while(getchar()!='\n');
} while(strcmp(s,"end\n")!=0);
free(s);
return 0;
}
问题在于它会产生错误的输出,stdin不会在“ do while”的每次迭代中产生“干净”的结果。我知道我必须在Windows上使用,fflush(stdin)
但在Internet上观看时,我发现此功能不适用于Linux。我使用linux,并且经常在互联网上观看,我看到很多人说解决方案while(getchar()!='\n);
不是fflush(stdin)
,但是问题没有解决...您能解释一下为什么吗?
我看到的问题:
您将错误的论据传递给write
。代替
write(STDERR_FILENO, s, MAX_SIZE);
它应该是
write(STDERR_FILENO, s, r); // Write the number of characters that were read
// not MAX_SIZE
跳到最后一行的策略还没有被深思熟虑。你有:
int r = read(STDIN_FILENO, s, MAX_SIZE);
if(r==-1) printf("error");
else{
write(STDERR_FILENO, s, MAX_SIZE);
}
while(getchar()!='\n');
首先,read
遇到换行符时不会停止阅读。它将读取最多MAX_SIZE
字符。在此过程中,它将占用尽可能多的换行符。您需要做的是fgets()
代替使用。
char* cp = fgets(s, MAX_SIZE, stdin);
if ( cp == NULL )
{
// If fgets fails, you probably reached the end of the file.
break;
}
fprintf(stderr, "%s", s);
线
while(strcmp(s,"end\n")!=0);
如果您用来read
从文件中读取数据,将导致不确定的行为,因为read
它不会自动向中添加终止的空字符s
。使用fgets
可以避免该问题。
另外,由于您知道编译时数组的大小,因此可以使用:
char s[MAX_SIZE];
而不是malloc
在运行时分配内存。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句