Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...