C++学习 --- 文件操作

1、文本文件
1.1、写文件

cout 屏幕输出流对象

#include <iostream>
#include <string>
#include <fstream>
using namespace std;
//文本文件,写文件
void test01() {
    //1、包含头文件 fstream
    //2、创建输出流文件对象
    ofstream ofs;
    //3、指定打开的方式
    ofs.open("text.txt",ios::out);
    //4、写内容
    ofs << "姓名: 张三" << endl;
    ofs << "性别: 女" << endl;
    ofs << "年龄: 22" << endl;
    //5、关闭文件
    ofs.close();
}
​
int main(){
    test01();
​
    system("pause");
    return 0;
}

 

1.2、读文件

#include <iostream>
#include <string>
#include <fstream>
using namespace std;
//文本文件,读文件
void test01() {
    //1、包含头文件
    //2、创建输入流文件对象
    ifstream ifs;
​
    //3、打开文件并且判断是否打开成功
    ifs.open("text.txt", ios::in);
    if (!ifs.is_open()) {
        cout << "文件打开失败" << endl;
        return;
    }
    cout << "文件打开成功" << endl;
    //4、读数据
    //第一种
    //char buf[4096] = { 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 ) {//EOF end of file
    //  cout << c;
    //}
//5、关闭文件
    ifs.close();
}
​
int main(){
    test01();
​
    system("pause");
    return 0;
}

 

2、二进制文件

2.1、写文件

#include <iostream>
#include <string>
#include <fstream>
using namespace std;
//二进制文件,写文件
class Person {
public:
    char m_Name[64];   //姓名
    int m_Age;         //年龄
};
​
void test01() {
    //1、包含头文件
    
    //2、创建流对象
    //ofstream ofs;
    ofstream ofs("person.txt", ios::out | ios::binary);
    
    //3、打开文件
    //ofs.open("person.txt", ios::out | ios::binary);
    
    //4、写文件
    Person p = {"张三",22};
    ofs.write( (const char *)&p, sizeof(Person));
    
    //5、关闭文件
    ofs.close();    
}
​
int main(){
    test01();
​
    system("pause");
    return 0;
}

 

2.2、读文件

#include <iostream>
#include <string>
#include <fstream>
using namespace std;
//二进制文件,读文件
class Person {
public:
    char m_Name[64];   //姓名
    int m_Age;         //年龄
};
​
void test01() {
    //1、包含头文件
//2、创建流对象
    ifstream ifs;
​
    //3、打开文件,判断文件是否打开成功
    ifs.open("person.txt", ios::in | ios::binary);
    if(!ifs.is_open()) {
        cout << "文件打开失败" << endl;
    }
    cout << "文件打开成功" << endl;
    //4、读文件
    Person p;
    ifs.read((char *)&p,sizeof(Person));
    cout << "姓名: " << p.m_Name << "\t年龄: " << p.m_Age << endl;
    //5、关闭文件
    ifs.close();
}
​
int main() {
    test01();
​
    system("pause");
    return 0;
}

 

 

posted @ 2021-08-24 11:41  yiwenzhang  阅读(55)  评论(0编辑  收藏  举报