Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
283 views
in Technique[技术] by (71.8m points)

c - Why are extra garbage characters printed?

I try to use read() to get some characters from file just for learning this API. I have create a file called "file" in the same directory and it is content:

1:2:ab:cd:ef

Here is the code:

#include <stdio.h>
#include <error.h>

int read_indent(int sockfd){
  int sport, cport;
  char user[3], rtype[3], addinfo[3];
  char buffer[4+4+3+3+3+1];

  if(read(sockfd, buffer, sizeof(buffer)) <= 0) {
    perror("read: %m");
    return -1;
  }

  buffer[sizeof(buffer)-1] = '';

  sscanf(buffer, "%d:%d:%s:%s:%s", &sport, &cport, rtype, user, addinfo);
  printf("%d:%d:%s:%s:%s", sport, cport, rtype, user, addinfo);
  return 0;
}

int main(){
  FILE *file_pt = fopen("file", "r");
  if(file_pt == NULL) { printf("fopen error
"); return -1;}
  char buf[128];
  int a = read_indent(fileno(file_pt));
  fclose(file_pt);
  return 0;
}

My printf returns me

1:2:ab:cd:ef::xPvx

where x is some garbage character I cannot recognize. What is the reason for this? int is 4 bytes in my system.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

One issue is that you didn't specify a width for the %s parameters. This means that it matches up until the first whitespace character. There are no whitespace characters in your string, so the first %s matches until the end, leaving only garbage data after your string to fill the other variables.

Try this:

sscanf(buffer, "%d:%d:%2s:%2s:%2s", &sport, &cport, rtype, user, addinfo);

The other issue is that you don't null-terminate your buffer properly, read returns the number of characters read - add a null after that.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...