文件处理:输出中的额外字符
#include <stdio.h>
int main () {
FILE *fp;
char ch;
char data[100];
int i;
fp = fopen("file.txt","r");
i=0;
while( (ch=fgetc(fp)) != EOF) {
data[i]=ch;
i++;
}
i=0;
while(data[i]) {
printf("%c",data[i]);
i++;
}
return 0;
}
file.txt 的内容:
udit@udit-Dabba /opt/lampp/htdocs $ cat file.txt
aGVsbG9teW5hbWVpc2toYW4K
程序的输出:
udit@udit-Dabba /opt/lampp/htdocs $ sudo vim test.c
udit@udit-Dabba /opt/lampp/htdocs $ sudo gcc test.c
udit@udit-Dabba /opt/lampp/htdocs $ ./a.out
aGVsbG9teW5hbWVpc2toYW4K
P�udit@udit-Dabba /opt/lampp/htdocs $
为什么这两个额外的字符出现在数组的输出中......??? 输入文件实际上是 Base-64 编码的结果。
#include <stdio.h>
int main () {
FILE *fp;
char ch;
char data[100];
int i;
fp = fopen("file.txt","r");
i=0;
while( (ch=fgetc(fp)) != EOF) {
data[i]=ch;
i++;
}
i=0;
while(data[i]) {
printf("%c",data[i]);
i++;
}
return 0;
}
Content of file.txt :
udit@udit-Dabba /opt/lampp/htdocs $ cat file.txt
aGVsbG9teW5hbWVpc2toYW4K
Output of Program :
udit@udit-Dabba /opt/lampp/htdocs $ sudo vim test.c
udit@udit-Dabba /opt/lampp/htdocs $ sudo gcc test.c
udit@udit-Dabba /opt/lampp/htdocs $ ./a.out
aGVsbG9teW5hbWVpc2toYW4K
P�udit@udit-Dabba /opt/lampp/htdocs $
Why these two extra characters appearing in the output of array...???
The input file is actually outcome of base-64 encoding.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
fgetc 返回
int
而不是字符
。看看这是否适合您:
fgetc returns an
int
not achar
.See if this works out for you:
您没有终止 data[] 数组 - 没有什么可以在输入末尾添加零,因此当您将其写出时,您会继续在数据末尾打印额外的(随机)值,直到您碰巧打零,
记住数据没有初始化为 c 中的任何内容
You aren't terminating the data[] array - there is nothing to put a zero at the end of the inpout, so when you write it out you keep printing the extra (random) values at the end of the data until you happen to hit a zero,
Remember data isn't initialized to anything in c
看起来像是因为您在开始之前没有将数据设置为零。 尝试添加
在阅读之前 。额外的输出是在您开始使用它之前内存中该位置发生的内容。
It looks like its because you didn't set data to zeros before you started. Try adding
before you read. The extra output is what happened to be in memory at that location before you started using it.
第一个循环以
EOF
终止,您不会将其写入data
数组(因为您不能)。第二个循环以
'\0'
终止,该'\0'
不在data
数组中。我建议您在阅读
EOF
后添加终止'\0'
。The first loop terminates with
EOF
, which you don't write to thedata
array (because you can't).The second loop terminates with a
'\0'
which is nowhere in thedata
array.I suggest you add the terminating
'\0'
once you read theEOF
.