C/C++语言实现文件操作

1、如下代码可实现对文件大小得读取,并读取特定长度存取到特定位置。其中seekg可以移动文件流得其实位置,进而从不同位置读取不同长度得数据。

    std::ifstream t;
    int length;
    t.open(strFileName.c_str());     // open input file
    t.seekg(0, std::ios::end);       // go to the end
    length = t.tellg();              // report location (this is the length)
    t.seekg(0, std::ios::beg);       // go back to the beginning
    char *buffer = new char[length]; // allocate memory for a buffer of appropriate dimension
    t.read(buffer, length);          // read the whole file into the buffer
    t.close();                       // close file handle

2、判断文件是否存在 

//通过读看文件是否存在
FILE *pf = fopen(fileName, "r");
if (NULL == pf)
{
    return FALSE;
}
else
{
    fclose(pf);
    return TRUE;
}

//判断文件是否存在另一种方式
if((access(fileName,F_OK))!=-1)
 {
    printf("file not exist.\n");
    return;
 }

3、从文件A中读取数据进行加解密后写入B文件中,类似文件加解密操作(代码直接拷贝需要修改)

#define BUFFER_SIZE                1024

char buffer[BUFFER_SIZE];
bzero(buffer, sizeof(buffer));

int file_block_length = 0;
FILE *fpIn = fopen(fileName,"rb");
if(fpIn==NULL)
{
    return false;
}
FILE *fpOut = fopen(newFileName,"wb");
if(fpOut==NULL)
{
    fclose(fpIn);
    return false;
}

while((file_block_length = fread(buffer, sizeof(char), BUFFER_SIZE, fpIn)) > 0)
{
    fwrite(buffer,sizeof(char),file_block_length,fpOut);
}
fclose(fpIn);
fclose(fpOut);

5、类似1的功能实现读取文件大小读取文件内容等的操作。

    char *buffer;
    FILE *pf = fopen(szCertPath, "r");
    if (NULL == pf)
    {
        return FALSE;
    }
    fseek(pf, 0, SEEK_END);
    long length = ftell(pf);
    buffer = (char *)malloc(length + 4);
    memcpy(buffer, &length, 4);
    rewind(pf);
    fread(buffer + 4, sizeof(char), length, pf);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值