多余的乱码为什么打印? [英] Why are extra garbage characters printed?
问题描述
我尝试使用read(),以获得从文件中的某些字符只是为了学习这个API。我创建一个在同一目录中名为文件的文件,它是内容:
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
下面是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] = '\0';
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\n"); return -1;}
char buf[128];
int a = read_indent(fileno(file_pt));
fclose(file_pt);
return 0;
}
我的printf返回我
My printf returns me
1:2:ab:cd:ef::xPvx
其中, X
是一些垃圾字符我无法识别。究竟是什么原因呢? INT
为4个字节在我的系统。
where x
is some garbage character I cannot recognize. What is the reason for this? int
is 4 bytes in my system.
推荐答案
一个问题是,你没有指定%S
参数的宽度。这意味着,它匹配,直到第一空白字符。有你的字符串中没有空白字符,所以第一个%S
匹配到最后,你的字符串,以填补其他变量后只留下垃圾数据。
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.
试试这个:
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.
这篇关于多余的乱码为什么打印?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!