//从文件中读取数据
//step1:打开fopen;
//step1:读取fread;
//step2 : 关闭;
#include<iostream>
using namespace std;
#include<stdio.h>
#include<windows.h>
FILE* stream;
errno_t err;
//用来读取数据调用的open
int open()
{
if ((err = (fopen_s(&stream, "d:/text.txt", "rb")) != 0)) //最后的"rb" 表示只读 wb :覆盖写入 ab:不覆盖写入{
cout << "filed open" << endl;
return -1;
}
else {
//cout << "success open" << endl;
return 0;
}
}
//用来写入数据调用的open
int open1()
{
if ((err = (fopen_s(&stream, "d:/text.txt", "ab")) != 0)) {
cout << "filed open" << endl;
return -1;
}
else {
//cout << "success open" << endl;
return 0;
}
}
struct Student
{
int id;
char name[12];
char sex[4];
};
//用来写入数据调用函数open1
int save()
{
char buf[12];
Student hd{ 13,"hdd","man" };
open1();
fwrite(&hd.id, 1, 1, stream);
fwrite(&hd.name, 1, 12, stream);
fwrite(&hd.sex, 1, 4, stream);
_fcloseall();
return 0;
}
//加载读取数据(缓存区buf:每次读取的规定大小)
int load()
{
//size_t fread(void* buf, //存储到目标内存地址
// size_t size, //设为1
// size_t nelem, //最多读取多个字节
// FILE * stream);
返回值:实际读取到的字节个数;
open();
/*char buf[128];
int n = fread(buf, 1, 128, stream);
cout << n << endl;*/
char buf[4]; //缓冲区每次读取4字节
while (!feof(stream))//用来检查stream所指的文件是否已到达末尾 到达时返回1
{
int n = fread(buf, 1, 4, stream);
//下面的用来打印文件内容
if (n > 0) {
cout << "read" << n << " bytes" << endl;//打印每次实际读取的大小
for (int i = 0; i < 4; i++){
cout << hex<<" " << (int)buf[i] ;//可以打印输出缓冲区内容
}
}
}
return 0;
}
int main()
{
save(); //注意不可以一直save ,否则会一直写入数据
DOWRD dwStart=GetTickCount(); //获取初始时间
load();
DWORD dwEnd=GetTickCount();
cout<<"time suing"<<dwEnd-dwStart<<endl;
cout << " eqqual "<< dec <<ftell(stream) << endl; //ftell(文件指针) 函数用来计算文件大小
_fcloseall();
return 0;
}
C++ 对文件数据进行写入读取
最新推荐文章于 2024-05-18 10:02:23 发布