开发者

File handling : Extra characters in output

#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-6开发者_StackOverflow社区4 encoding.


fgetc returns an int not a char.

See if this works out for you:

#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;

 }


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

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

before you read. The extra output is what happened to be in memory at that location before you started using it.


The first loop terminates with EOF, which you don't write to the data array (because you can't).

The second loop terminates with a '\0' which is nowhere in the data array.

I suggest you add the terminating '\0' once you read the EOF.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜