c++文件读取

#include<stdio.h>
#include<string.h>
#include<iostream>
using namespace std;
struct info
{
    int len;
    char code[4];
    char content[];
};

void writeText()
{
    int len1 = 12;
    string str1 = "aaaa";
    string str11= "bbbb";

    int len2 = 10;
    string str2 = "cccc";
    string str22 = "dd";

    int len3 = 9;
    string str3 = "eeee";
    string str33 = "f";

    FILE* pFILE = fopen("./test.dat", "wb");
    size_t  wBytes = fwrite(&len1, 1, sizeof(int), pFILE);
    wBytes = fwrite(str1.c_str(), 1, str1.size(), pFILE);
    wBytes = fwrite(str11.c_str(), 1, str11.size(), pFILE);

    wBytes = fwrite(&len2, 1, sizeof(int), pFILE);
    wBytes = fwrite(str2.c_str(), 1, str2.size(), pFILE);
    wBytes = fwrite(str22.c_str(), 1, str22.size(), pFILE);

    wBytes = fwrite(&len3, 1, sizeof(int), pFILE);
    wBytes = fwrite(str3.c_str(), 1, str3.size(), pFILE);
    wBytes = fwrite(str33.c_str(), 1, str33.size(), pFILE);

    fclose(pFILE);
}

void appendText()
{
    FILE* pFile = fopen("./test.dat", "ab+");
    int len = 13;
    string a = "mmmm";
    string b = "zzzzz";
    size_t wBytes = fwrite(&len, 1, sizeof(int), pFile);
    wBytes = fwrite(a.c_str(), 1, a.size(), pFile);
    wBytes = fwrite(b.c_str(), 1, b.size(), pFile);
    fclose(pFile);
}

void readText()
{
    FILE* pFile = fopen("./test.dat", "rb");
    fseek(pFile, 0 ,SEEK_END);
    size_t file_len =ftell(pFile);
    rewind(pFile);
    char* buff = new char[file_len+1];
    size_t rBytes = fread(buff, 1, file_len, pFile);
    buff[file_len] = '\0';
    int idx = 0;
    while(idx < file_len)
    {
        int len;
        memcpy(&len, buff + idx, sizeof(int));
        struct info tmp;
        memset(&tmp, 0 , len);
        memcpy(&tmp, buff + idx, len);

        char* a = new char[5];
        memcpy(a, tmp.code, 4);
        a[4] = '\0';

        char* b =new char[len-7];
        memcpy(b ,tmp.content, len-8);
        b[len-8] = '\0';
        
        cout<<len<<endl<<a<<endl<<b<<endl;
        delete[] a;
        delete[] b;
        a = nullptr;
        b = nullptr;
        idx += len;
    }
}

int main()
{
    //writeText();
    //appendText();
    readText();
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值