C++ 核心编程 文件操作

时间:2021-09-16
本文章向大家介绍C++ 核心编程 文件操作,主要包括C++ 核心编程 文件操作使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
#include <iostream>
using namespace std;
#include <fstream>
//读文件的操作函数
void read() {
    //1、包含读写文件的头文件 #include <fostream>
    //2、创建读文件的对象
    ofstream fos;
    //3、指定以什么样的方式去打开一个文件
    fos.open("test.txt",ios::out);
    //4、写内容
    fos << "姓名:宫健丽" << endl;
    fos << "性格:活泼开朗" << endl;
    //5、关闭文件

}
int main() {
    read();

    system("pause");

    return 0;

}
#include <iostream>
using namespace std;
#include <fstream>
#include <string>



void write() {
    //1、包含头文件
    //2、创建流对象
    ifstream ifs;
    //3、以哪种方式读文件,并判断是否正常打开
    ifs.open("test.txt", ios::in);

    if (!ifs.is_open()) {

        cout << "文件打开方式有错" << endl;

    }
    //4、读文件
    //分别是4种打开方式
    //第一种
    //char buf[1024] = { 0 };//用数组buf去接收,{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;
    }

    //5、关闭文件
    ifs.close();


}
int main() {
    
    //char buf[1024] = {0};//{0} 是初始化字符数组
    write();

    system("pause");
    return 0;
}
#include <iostream>
using  namespace std;
#include <fstream>
//二进制文件  写文件


class Person
{
public:
        char m_Name[64];
        int m_Age;
};
//二进制写
void test01() {
    ofstream ofs;
    ofs.open("person.txt", ios::out | ios::binary);
    Person p = { "张三",18 };
    ofs.write((const char*)&p,sizeof(Person));
    ofs.close();

}

//二进制读
int main() {

    test01();
    system("pause");
    return 0;
}
#include <iostream>
using  namespace std;
#include <fstream>
//二进制文件  写文件


class Person
{
public:
        char m_Name[64];
        int m_Age;
};
//二进制写
void test01() {
    ofstream ofs;
    ofs.open("person.txt", ios::out | ios::binary);
    Person p = { "张三",18 };
    ofs.write((const char*)&p,sizeof(Person));
    ofs.close();

}

//二进制读
void test02() {

    ifstream ifs;
    ifs.open("person.txt", ios::in | ios::binary);
    if (!ifs.is_open()) {
        cout << "打开失败" << endl;
        return;
    }
    Person p;
    ifs.read((char *)&p, sizeof(Person));
    cout << "姓名:" << p.m_Name << "年龄" << p.m_Age << endl;
    ifs.close();
}
int main() {

    /*test01();*/
    test02();
    system("pause");
    return 0;
}

原文地址:https://www.cnblogs.com/gjianli/p/15292492.html