开发者

Not getting all characters after reading from file

#include<stdio.h>
#include<stdlib.h>

int main()
{
        int count=0;
        char c=0;
        printf("Reading this Source file\nFile name is: %s\n",__FILE__);
        FILE *myFile=fopen(__FILE__,"r");

        if(myFile)
            printf("File Successfully Opened\n");   
        do{
      开发者_如何学编程      c=fgetc(myFile);
            count++;
        } while(c!=EOF);

        printf("%s contains %d characters\n",__FILE__,count);   
        char *p=(char*)malloc(count+1);

        if(p==NULL)
            printf("Malloc Fail\n");

        else
        {
            fseek(myFile,0,SEEK_SET);
            printf("\nMalloc succeeded - You have %d Bytes of Memory\n",count+1);
            fgets(p,count,myFile);
            printf("The Entire Source Code is\n---------------------------\n");
            int i=0;
            while(i<count) 
                 printf("%c",*(p+i++));   
        }

        free(p);
        fclose(myFile); 
        return 0;
}

In the above program I keep getting only up to the following characters:

#include<stdio.h>

That is my output is:

Reading this Source file
File name is: main.c
File Successfully Opened

main.c contains 704 characters
Malloc succeeded - You have 705 Bytes of Memory
The Entire Source Code is
#include<stdio.h>

Why is the entire content of file not being shown in the output?


Because fgets stops at newline.

fgets(p,count,myFile); /* Stops when it reaches `count` OR at newline. */

EDIT

Use fread instead or use the first loop (the one with fgetc) to store the characters and expand p as you go.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜