[英]fprintf printing garbage characters
I have the following block of code:我有以下代码块:
while(true){
if(feof(stdin)!=0){
break;
}
fgets(fileText2,1000,stdin);
//flag E
if(strchr(flags,'A')||strchr(flags,'E')){
if(fileText2!=NULL&&strlen(fileText2)>0){
fileText2[strlen(fileText2)-1]='$';
fileText2[strlen(fileText2)]='\n';
fileText2[strlen(fileText2)+1]='\0';
}
}
fprintf(stdout,"%s",fileText2);
memset(fileText2,0,1000);
}
I am redirecting the contents of a file to the standard input using the <
operator.我正在使用<
运算符将文件的内容重定向到标准输入。
The file looks like:该文件如下所示:
omcunneecnucnwencnwecwe
cwec
c
wc
wec
wc
wec
wec
ecwccwc
wec
wecw we
ew
e
wecwe
c we e ewwe ewwe
w
we
wec
ec
ceec
and is a unix line termination file.并且是 unix 线路终止文件。 The first line it prints the omcunneecnucnwencnwecwe
, but before printing the second sentence ( cwec
), it prints some garbage characters.第一行打印omcunneecnucnwencnwecwe
,但在打印第二句 ( cwec
) 之前,它打印了一些垃圾字符。 This only happens after the first line, and all others are fine.这只发生在第一行之后,所有其他都很好。
The following is an example of the output:以下是 output 的示例:
omcunneecnucnwencnwecwe$
h_cwec$
c$
wc$
wec$
wc$
wec$
wec$
ecwccwc $
wec$
wecw we $
ew$
e$
wecwe$
c we e ewwe ewwe $
w$
we$
wec$
ec$
$
$
ceec$
How do I get rid of those garbage characters?我如何摆脱那些垃圾字符? (The dollar characters are not garbage, only the second line ones before the actual sentence in the file) (美元字符不是垃圾,只有文件中实际句子之前的第二行)
EDIT: fileText2
is defined as char fileText2[1000];
编辑: fileText2
定义为char fileText2[1000];
This overwrites the trailing null character .这会覆盖结尾的null 字符。
fileText2[strlen(fileText2)]='\n';
Now strlen(fileText2)
below is bad as fileText2
is no longer certainly null character terminated - not a string .现在下面的strlen(fileText2)
很糟糕,因为fileText2
不再肯定是 null 字符终止 - 不是字符串。
fileText2[strlen(fileText2)+1]='\0'; // UB
When fgets()
return NULL
(when end-of-file occurs),当fgets()
返回NULL
时(发生文件结束时),
fgets(fileText2,1000,stdin);
Then the following strlen(fileText2)
reflects the previous line.然后下面的strlen(fileText2)
反映了上一行。
Instead:反而:
//while(true){
// if(feof(stdin)!=0){
// break;
// }
// fgets(fileText2,1000,stdin);
while (fgets(fileText2, sizeof fileText2, stdin)) {
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.