目录
写文件
#include<iostream> using namespace std; //#include<string> #include<fstream> //头文件 void test() { ofstream ofs; //创建流对象 ofs.open("新建文本文档.txt", ios::out); //打开文件,选择打开方式(ios::out为写文件 方式) ofs << "清明时节雨纷纷,路上行人欲断魂" << endl; //写入 ofs << "借问酒家何处有,牧童遥指杏花村" << endl; //写入 ofs.close(); //关闭 } int main() { test(); }
(若没有先创建文档,会在cpp文件夹下自动创建)
读文件
#include<iostream> using namespace std; #include<string> #include<fstream> //头文件 void test() { ifstream ifs; //创建流对象 ifs.open("新建文本文档.txt", ios::out); //打开文件,选择打开方式 if (!ifs.is_open()) { //判断是否存在该文件等 cout << "文件打开失败" << endl; return; } //读数据方式 /* //第一种 char buf[1024] = { 0 }; while (ifs>>buf) { cout << buf << endl; } //第二种 char buf1[1024] = { 0 }; while (ifs.getline(buf1,sizeof(buf1))) { cout << buf1 << endl; } */ //第三种 string buf2; while (getline(ifs, buf2)) { cout << buf2 << endl; } ifs.close(); //关闭 } int main() { test(); }
二进制写文件
#include<iostream> using namespace std; #include<string> #include<fstream> //头文件 class student { public: student(int a) { age = a; } int age; }; void test() { //第一步 /*ofstream ofs; ofs.open("新建文本文档.txt", ios::out | ios::binary);*/ //↓合并↓// ofstream ofs("新建文本文档.txt", ios::out | ios::binary);// 写文件 | 二进制方式 //第二步 student stu(18); ofs.write((const char *)&stu,sizeof(student)); //第三步 ofs.close(); } int main() { test(); }
二进制读文件
(读取上条存好的二进制数据)
#include<iostream> using namespace std; #include<string> #include<fstream> //头文件 class student { public: student() {}; student(int a) { age = a; } int age; }; void test() { //第一步 创建一个输入流对象(?) ifstream ifs("新建文本文档.txt",ios::in|ios::binary ); if (!ifs.is_open()) { cout << "打开失败" << endl; return; } //第二步 读对象 student stu; ifs.read((char*)&stu,sizeof(student));//将二进制文件的东西赋予给对象 cout << "学生年龄::" << stu.age << endl; //第三步 关闭文件 ifs.close(); } int main() { test(); }
out:我的输出出去
in:东西输入进来,让我打印
创建流对象和open操作可合并
打开操作加这个严谨一点
if (!ifs.is_open()) { cout << "打开失败" << endl; return; }
检测是否为空
char ch; ifs >> ch;//往右读一个字符 if (ifs.eof()) {//监测文件是否为空 cout << "文件为空" << endl; return; }
读取文件中的数字
挺神奇,遇到整型进入循环,没遇到整型也不会跳出循环。直到遇到终止符。
ifs将读到的整型暂存与a? ↓
缺点:
读到一个整型+1。但一旦读到不是整型的,就会跳出循坏,从而读不到后面
改进:暂时想不到