阅读耗时大概 1分钟
| 数据类型 | 描述 |
|---|---|
| ofstream | 写操作 |
| ifstream | 读操作 |
| fstream | 读写操作 |
使用文件操作需要用到 fstream头文件
文件保存访问,以文本ASCII码形式存储、或者二进制形式存储
文件打开方式
| 方式 | 描述 |
|---|---|
| ios::in | 读文件而打开文件 |
| ios::out | 为写文件而打开文件 |
| ios::ate | 初始位置:文件尾 |
| ios::trunc | 如果文件存在先删除,再创建 |
| ios::binary | 二进制方式 |
| ios::cur | 从流的当前位置开始定位 |
| ios::end | 从流的末尾开始定位 |
| ios::beg | 默认的,从流的开头开始定位 |
读写文件示例
using namespace std;#include <iostream>#include <fstream>class Person{public:char m_Name[64];int m_Age;};int main(){// ofstream ofs;// ofs.open("person.txt", ios::out | ios::binary);// Person p = {"张三", 18};// ofs.write((const char *)&p, sizeof(Person));// ofs.close();ifstream ifs;ifs.open("person.txt", ios::in | ios::binary);if(ifs.is_open()){cout << "打开成功" << endl;Person p;ifs.read((char *) &p, sizeof(Person));ifs.close();cout << p.m_Name << " / " << p.m_Age << endl;}return 0;}
ios::out | ios::binary 为写文件打开文件,并以二进制方式写入
打开文件的函数如下void open(const char *filename, ios::openmode mode);istream中有一个seekg新定位文件位置指针的成员函数 和 ostrem中有一个seekp
// 定位到 fileObject 的第 n 个字节(假设是 ios::beg)fileObject.seekg( n );// 把文件的读指针从 fileObject 当前位置向后移 n 个字节fileObject.seekg( n, ios::cur );// 把文件的读指针从 fileObject 末尾往回移 n 个字节fileObject.seekg( n, ios::end );// 定位到 fileObject 的末尾fileObject.seekg( 0, ios::end );
写两个示例差不多就入门了
#include <fstream>#include <iostream>using namespace std;int main (){char data[100];// 以写模式打开文件ofstream outfile;outfile.open("afile.dat");cout << "Writing to the file" << endl;cout << "Enter your name: ";cin.getline(data, 100); //从外部读取一行// 向文件写入用户输入的数据outfile << data << endl;cout << "Enter your age: ";cin >> data;cin.ignore(); //ignore() 函数会忽略掉之前读语句留下的多余字符// 再次向文件写入用户输入的数据outfile << data << endl;// 关闭打开的文件outfile.close();// 以读模式打开文件ifstream infile;infile.open("afile.dat");cout << "Reading from the file" << endl;infile >> data;// 在屏幕上写入数据cout << data << endl;// 再次从文件读取数据,并显示它infile >> data;cout << data << endl;// 关闭打开的文件infile.close();return 0;}
#include <fstream>#include <iostream>#include <fstream>#include <string>using namespace std;int main(){//1.读文件// ofstream ofs;// ofs.open("test.txt", ios::out);// ofs << "姓名 张三" << endl;// ofs.close();//2.读文件ifstream ifs;//判断文件并判断文件是否打开成功ifs.open("test.txt", ios::in);if(ifs.is_open()){cout << "文件打开成功" << endl;//char buf[1024] = {0};//2.1// while (ifs >> buf)// {// cout << buf << endl;// }//2.2// while(ifs.getline(buf, sizeof(buf))){// cout << buf << endl;// }//2.3// string buf;// while(getline(ifs, buf)){// cout << buf << endl;// }//2.4// char c;// while((c = ifs.get()) != EOF){// cout << c ;// }// ifs.close();}return 0;}
