1、简介:
数据存储的两种方式:文件和数据库
IOS_base是基类派生出IOS类
IOS派生出-istream类和ostream类
istream定义cin
ostream定义cout、cerr、clog
istream类派生出,ifstream读文件
ostream类派生出,ofstream写文件
istream和ostream派生出iostream类
iostream派生出fstream类,读写文件

2、写入文件
文本文件一般以行的形式组织数据
头文件:#include <fstream>
类:ofstream(output file stream)
C语言我一般习惯用fprintf,把数据写入文件
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <fstream>//oftream类需要包含的头文件
using namespace std;
int main()
{
string file = "E:\\C\\visualStudio\\project_management\\C++_sys_test\\test.txt";
//ofstream fout;//file output文本输出对象
//fout.open(file);
ofstream fout(file,ios::out);//类似于c的w
//ofstream fout(file, ios::app);//类似于c的a
if (!fout.is_open()) {
cout << "open fail:" <<file << endl;
return 1;
}
fout << "nike 18 90" << endl;
fout << "adidas 20 99" << endl;
fout << "senma 28 93" << endl;
fout.close();//关闭文件,fout对象失效前会自动调用close();
return 0;
}
nike 18 90
adidas 20 99
senma 28 93
3、读取文件
包含头文件:#include <fstream>
类:ifstream
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <fstream>//oftream类需要包含的头文件
#include <string>
using namespace std;
int main()
{
string file = "E:\\C\\visualStudio\\project_management\\C++_sys_test\\test.txt";
//ofstream fout;//file output文本输出对象
//fout.open(file);
ifstream fin(file,ios::in);//读取
if (!fin.is_open()) {
cout << "open fail:" <<file << endl;
return 1;
}
//第一种方法
//string buffer;
//while (getline(fin, buffer)) {
// cout << buffer << endl;
//}
//第二种方法
//char buffer[101];
////一定要保证缓冲区足够大
//while (fin.getline(buffer, 100)) {
// cout << buffer << endl;
//}
//第三种方法
string buffer;
while (fin >> buffer) {
cout << buffer << endl;
}
fin.close();//关闭文件,fout对象失效前会自动调用close();
return 0;
}
4、以二进制方式打开文件
ios::binary
fout.open(file,ios::app | ios::binary);
fout.write((const char*)&girl,sizeof(st_girl));
5、读取二进制文件
二进制文件格式多种多样
程序员定义的二进制格式,只有自己知道
通用的二进制文件格式:mp3、mp4、bmp、jpg、png
fin.read((char *)&girl,sizeof(girl)))

被折叠的 条评论
为什么被折叠?



