user12184817
user12184817

Reputation:

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. The first line it prints the omcunneecnucnwencnwecwe, but before printing the second sentence (cwec), it prints some garbage characters. This only happens after the first line, and all others are fine.

The following is an example of the 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];

Upvotes: 1

Views: 127

Answers (1)

chux
chux

Reputation: 153447

This overwrites the trailing null character.

fileText2[strlen(fileText2)]='\n';

Now strlen(fileText2) below is bad as fileText2 is no longer certainly null character terminated - not a string.

fileText2[strlen(fileText2)+1]='\0';  // UB

When fgets() return NULL (when end-of-file occurs),

fgets(fileText2,1000,stdin);

Then the following strlen(fileText2) reflects the previous line.

Instead:

//while(true){
//  if(feof(stdin)!=0){
//    break;
//  }
//  fgets(fileText2,1000,stdin);
while (fgets(fileText2, sizeof fileText2, stdin)) {
  ...

Upvotes: 2

Related Questions