c - 从文件读取后未获取所有字符

标签 c

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

在上面的程序中,我一直只获取以下字符:

#include<stdio.h>

我的输出是:

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>

为什么文件的全部内容没有显示在输出中?

最佳答案

因为 fgets 在换行处停止。

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

编辑

改用 fread 或使用第一个循环(带有 fgetc 的循环)来存储字符并在运行时展开 p

关于c - 从文件读取后未获取所有字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7763025/

相关文章:

c - 是否可以直接从 C 源代码传递 GCC 参数?

c - 在结构中存储多维数组

c - 添加到 c 中的现有结构

c - 请求分页上下文中的神秘数字 '63'

c - C中main之外的变量范围

c - 复制数组时的 gcc 优化

c - 在C中递归地将InOrder二叉搜索树数据放入数组中

c - execvp - 为什么我的程序退出?

c - Eclipse J-Link ATMEL ARM ATSAME70Q21。当代码的起始地址不同于 0x00400000 时进行调试

c - 尝试将结构体中的指针分配给二维数组