目录
1.C++文件读写
- ifstream:读取文件数据类
- ofstream:写入文件数据类
- fstream:读取和写入文件数据类
#include <iostream>
#include <fstream> //写和读头文件
using namespace std;
const int N = 5;
int main()
{
ofstream fout;
fout.open(".\\test.bin", ios::out | ios::binary); //打开写文件
//ios::binary:以二进制文件打开 ios::app:以追加方式打开文件
//或者使用 ofstream outFile("clients.dat", ios::out | ios::binary); //打开文件
if (!fout)
{
cerr << "File open error!" << endl;
}
long location = fout.tellp(); //取得写指针的位置
cout << "写指针的位置为:" << location << endl;
//写指针文件定位
//location = 10L;
//fout.seekp(location); //将写指针移动到第10个字节处
//fout.seekp(location, ios::beg); //从头开始数location个
//fout.seekp(location, ios::cur); //从当前位置数location个
//fout.seekp(location, ios::end); //从尾部数location个
//二进制文件写入
cout << "写入的数据为:";
int i = 0;
int data;
while (i < N)
{
cin >> data;
fout.write((const char*)(&data), sizeof(int));
i++;
}
//关闭文件
fout.close();
cout << "写入数据成功" << endl;
//===================================================================================
//读数据
//ifstream fin;
//fin.open(".//test.bin", ios::in | ios::binary); //打开读文件
//long location_in = fin.tellg();//取得读指针的位置
//cout << "读取数据的指针位置:" << location_in << endl;
二进制文件读取
//int data_in;
//while (fin.read((char*)(&data_in), sizeof(int)))
//{
// cout << "读出的输入为:"<< data_in << endl;
//}
//fin.close();
//cout << "读取数据成功" << endl;
//getchar();
}
2.C语言文件读写
#include <iostream>
#include <cstdio> //读写数据头文件
#include <string>
using namespace std;
const int N = 5;
int main()
{
FILE* fp_write, *fp_read;
//写入文件
string fname = ".\\test2.bin";
if ((fp_write = fopen(fname.c_str(), "wb+")) == NULL) //覆盖原有文件 +:读权限
{
cout << "could not open file!" << endl;
exit(1);
}
int i = 0;
int data;
while (i < 5)
{
cin >> data;
fread(&data, sizeof(int), 1, fp_write);
//读取输入
//fwrite(&data, sizeof(int), 1, fp_read )
}
fclose(fp_write);
}