- 文本文件:写文件
- 文本文件:读文件
- 二进制文件:写文件
- 二进制文件:读文件
程序运行的过程中产生的数据都属于临时数据 程序一旦结束运行的话这些数据也会被释放,所以就要通过文件来讲数据持久化
C++中对文件操需要包含头文件
文件一般分为两种类型:文本文件和二进制文件
- 文本文件:文件以文本的ASCLL码的形式存储在计算机内i
- 二进制文件:文件以文本的二进制形式存储在计算机内 用户一般不能直接读懂他们
操作文件的三大类:
- 写操作:ofstream
- 读操作:ifstream
- 读写操作:fstream
写文件得操作流程:
- 包含头文件
- 创建流对象 ofstream ofs
- 打开文件 ofs.open(“文件路径”,打开方式)
- 写数据ofs<<
- 关闭文件 ofs.close()
文件的打开方式主要有一下几种:
#include文本文件:读文件#include #include //c++中字符串需要添加这个头文件 #include using namespace std; int main() { ofstream ofs; ofs.open("E:\Users\Desktop\C++test.txt", ios::out); ofs << "C++ test 1" << endl; ofs << "C++ test 2" << endl; ofs.close(); system("pause"); return 0; }
读文件得操作流程:
- 包含头文件
- 创建流对象 ofstream ifs
- 打开文件并判断打开文件是否成功 ofs.open(“文件路径”,打开方式)
- 读数据 四种读取方式
- 关闭文件 ofs.close()
第一种方式
#include#include #include //c++中字符串需要添加这个头文件 #include using namespace std; int main() { ifstream ifs; ifs.open("E:\Users\Desktop\C++test.txt", ios::in); if (!ifs.is_open()) { cout << "打开文件失败!" << endl; return 0; } cout << "The first read way" << endl;//The first read way char str1[1024] = {0}; while (ifs >> str1) { cout << str1 << endl; } ifs.close(); system("pause"); return 0; }
第二种方式
#include#include #include //c++中字符串需要添加这个头文件 #include using namespace std; int main() { ifstream ifs; ifs.open("E:\Users\Desktop\C++test.txt", ios::in); if (!ifs.is_open()) { cout << "打开文件失败!" << endl; return 0; } cout << "The second read way" << endl;//The second read way char str[1024] = {0}; while (ifs.getline(str,sizeof(str))) { cout << str << endl; } ifs.close(); system("pause"); return 0; }
第三种方式
#include#include #include //c++中字符串需要添加这个头文件 #include using namespace std; int main() { ifstream ifs; ifs.open("E:\Users\Desktop\C++test.txt", ios::in); if (!ifs.is_open()) { cout << "打开文件失败!" << endl; return 0; } cout << "The third read way" << endl;//The third read way string str; while (getline(ifs,str)) { cout << str << endl; } ifs.close(); system("pause"); return 0; }
第四种方式
#include#include #include //c++中字符串需要添加这个头文件 #include using namespace std; int main() { ifstream ifs; ifs.open("E:\Users\Desktop\C++test.txt", ios::in); if (!ifs.is_open()) { cout << "打开文件失败!" << endl; return 0; } cout << "The fourth read way" << endl;//The fourth read way char str; while ( (str =ifs.get())!=EOF) { cout << str << endl; } ifs.close(); system("pause"); return 0; }
通过四种读文件的方式可以分析对比,第2,3种的方式都是按行读取的 是我们一般中比较常用的的方式
后期增加
二进制文件:读文件后期增加



