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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…