#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();
}
c++文件读取
最新推荐文章于 2023-03-03 21:59:56 发布