- 要点:
- ifstream:input。从文件中读取数据,输入到文件流对象。
- ofstream:output。文件流对象输出,写入数据到文件中,
- fstream:既可读取数据,也能写入数据。
- 文件读取必须遵循以下流程:打开文件 -> 读/写文件 -> 关闭文件。
-
C++中对文件操作需要
包含头文件#include
。
1、创建流对象:ofstream ofs;
2、打开文件:ofs.open("文件路径",打开方式);
3、写数据 :ofs << "写入的数据";
4、关闭文件 :ofs.close();
注意: 文件打开方式可以配合使用,利用 | 操作符 例如: 用 二进制方式写文件: ios::binary | ios:: out 二、读文件1、包含头文件:#include
2、创建流对象:ifstream ifs;
3、打开文件并判断文件是否打开成功:ifs.open("文件路径",打开方式);
4、读数据:四种方式读取
5、关闭文件:ifs.close();
#include#include using namespace std; void test01() { ifstream ifs; ifs.open("test.txt", ios::in); if (!ifs.is_open()) { cout << "文件打开失败" << endl; return; } //第一种方式 //char buf[1024] = { 0 }; //while (ifs >> buf) //{ // cout << buf << endl; //} //第二种 //char buf[1024] = { 0 }; //while (ifs.getline(buf,sizeof(buf))) //{ // cout << buf << endl; //} //第三种 //string buf; //while (getline(ifs, buf)) //{ // cout << buf << endl; //} char c; while ((c = ifs.get()) != EOF) { cout << c; } ifs.close(); } int main() { test01(); system("pause"); return 0; }



