停电一天之后,今天还有什么理由不学习呜呜……还是没怎么学习
目录
文件操作可以将数据持久化,对文件操作时须包含头文件
两种文件类型:文本文件:文件以文本的ASCII码形式存储;二进制文件:文件以文本的二进制形式存储
操作文件三大类:ofstream 写操作;ifsream读操作, fstream读写操作
包含头文件:#include
打开方式 :
ios::in 为读文件而打开文件
ios::out 为写文件而打开文件
ios::ate 初始位置:文件尾
ios::app 追加方式写文件
ios::trunc 如果文件存在先删除,再创建
ios::binary 二进制方式
注意:| 操作符,配合使用文件打开方式,IOS::BINARY | IOS::OUT——用二进制方式写文件;未指定完整文件夹路径,默认和源文件一起?
- #include <iostream>
- #include <fstream>
- using namespace std;
-
- void test01() {
- //创建流对象
- ofstream ofs;
- //指定打开方式 “文件路径”,打开方式
- ofs.open("test.txt", ios::out);
- //写内容
- ofs << "姓名 :张三" << endl;
- ofs << "性别:男" << endl;
- ofs << "年龄:18" << endl;
- //关文件
- ofs.close();
- }
- int main() {
- test01();
- system("pause");
- return 0;
- }
包含头文件:#include
字符数组while (ifs >> buff) 字符数组while (ifs.getline(buff2, sizeof(buff2)))
字符串【这里不可以省略
- #include <iostream>
- #include<string>
- #include <fstream>
- using namespace std;
-
- void test01() {
- ifstream ifs;
- ifs.open("test.txt", ios::in);
- if (!ifs.is_open()) { //is_open(),bool类型,!取反
- cout << "文件打开失败" << endl;
- return; //失败不继续进行
- }
- //读数据 第一种 输出上比其他多了一个换行符,不懂
- char buff[1024] = { 0 };//字符数组
- while (ifs >> buff) { //文件写入BUFF,没有数据的时候循环结束
- cout << buff << endl;
- }
-
- //第二种
- //char buff2[1024] = { 0 };
- //while (ifs.getline(buff2, sizeof(buff2))) {//GETLINE获取一行,char*,首地址,count最多读几个字节数【数组大小】
- // cout << buff2 << endl;
- //}//都不注释也只输出一次,不懂
-
- //第三种
- //string buff3;
- 基础的输入流,GETLINE基础的输入流,需要输入流对象IFS,准备好的字符串
- //while (getline (ifs,buff3)) { //未定义标识符getline?不懂
- // cout << buff3 << endl;
- //}//失败——加上<string>头文件
-
- //第四种,C,不常用,效率低
- /*char c;
- while ((c = ifs.get()) != EOF) {
- cout << c;
- }*/
-
- ifs.close();
- }
- int main() {
- test01();
- system("pause");
- return 0;
- }
打开要指定为ios::binary
二进制写文件主要利用流对象调用成员函数WRITE,函数原型:ostream& write ( const char* buffer,int len);解释:字符指针buffer指向内存中的一段存储空间,len是读写的字节数
二进制读入的文件会乱码,只要正确读入就不影响
- #include <iostream>
- #include<string>
- #include <fstream>
- using namespace std;
- class Person {
- public:
- char m_Name[64];//尽量用C的字符数组,STRING容易出现问题
- int m_Age;
- };
-
- void test01() {
- ofstream ofs;
- //打开头文件
- ofs.open("person.txt", ios::out | ios::binary);
- Person p = { "王五",78 };
- //对P取地址返回Person性质的地址,强制转换成CHAR*
- ofs.write((const char*)&p, sizeof(Person));
- ofs.close();
- }
- int main() {
- test01();
- system("pause");
- return 0;
- }
二进制读文件主要利用流对象调用成员函数READ,函数原型:istream& read ( const char* buffer,int len);解释:字符指针buffer指向内存中的一段存储空间,len是读写的字节数
- #include <iostream>
- #include<string>
- #include <fstream>
- using namespace std;
- class Person {
- public:
- char m_Name[64];//尽量用C的字符数组,STRING容易出现问题
- int m_Age;
- };
-
- void test01() {
- ifstream ofs;
- //打开头文件
- ofs.open("person.txt", ios::in | ios::binary);
- if (!ofs.is_open()) {
- cout << "打开失败" << endl;
- return;
- }
- //读文件
- Person p;
- ofs.read((char*)&p, sizeof(Person));
- //输出数据
- cout << "姓名:" << p.m_Name << "\t年龄:" <<p.m_Age<< endl;
- ofs.close();
- }
- int main() {
- test01();
- system("pause");
- return 0;
- }