linux读取整个文件

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

    FILE * pFile;
    long lSize;
    char * buffer;
    size_t result;
  
    /* 若要一个byte不漏地读入整个文件,只能采用二进制方式打开 */
    pFile = fopen ("./test/dd.txt", "rb" );
    if (pFile==NULL)
    {
        printf ("File error");
        exit (1);
    }
  
    /* 获取文件大小 */
    fseek (pFile , 0 , SEEK_END);
    lSize = ftell (pFile);
    rewind (pFile);
  
    /* 分配内存存储整个文件 */
    buffer= (char*) malloc (sizeof(char)*lSize);
    if (buffer== NULL)
    {
        printf ("Memory error");
        exit (2);
    }
  
    /* 将文件拷贝到buffer中 */
    result = fread (buffer,1,lSize,pFile);
    if (result != lSize)
    {
        printf ("Reading error");
        exit (3);
    }
    /* 现在整个文件已经在buffer中,可由标准输出打印内容 */
    printf("\n%s\n", buffer);
  
    /* 结束演示,关闭文件并释放内存 */
    fclose (pFile);
    free (buffer);

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值