0
#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 编码的结果。

4

4 回答 4

1

您没有终止 data[] 数组 - 在输入的末尾没有任何内容可以放置零,因此当您将其写出时,您会继续在数据末尾打印额外(随机)值,直到您碰巧打零,

记住数据没有初始化为c中的任何东西

于 2011-09-30T15:23:04.020 回答
1

看起来是因为您在开始之前没有将数据设置为零。尝试添加

memset(data,0,sizeof(data)); 

在你读之前。额外的输出是在您开始使用它之前发生在该位置的内存中的内容。

于 2011-09-30T15:23:43.287 回答
1

第一个循环以 结束EOF,您不会将其写入data数组(因为您不能)。

第二个循环以数组'\0'中无处的a 结束。data

我建议您在'\0'阅读EOF.

于 2011-09-30T15:24:25.833 回答
1

fgetc返回一个intnot a char

看看这是否适合你:

#include <stdio.h>

int main (void) {

    FILE *fp;
    int ch;
    int data[100] = { 0 }; // Easiest way of initializing the entire array to 0
    int i;

    fp = fopen("file.txt","r");

    i=0;

    while( (ch=fgetc(fp)) != EOF) {
            data[i]=ch;
            i++;
    }

//        data[i]=0; -->You did not provide a terminating point - 
// Not needed if the array is initialized the way i did.

    i=0;

    while(data[i]) {
           printf("%c",data[i]); 
            i++;  }
 return 0;

 }
于 2011-09-30T15:25:08.467 回答