c++文件的操作

文件操作:

c++对文件的操作需要包含头文件<fstream>

文件的类型,主要分为 文本文件(ASCII形式存在电脑)  和 二进制文件 。

文件操作方式:1.写文件(ofstream) 2.读文件(ifstream) 3.读写文件(fstream)

 

写文件步骤:

1.包含头文件 》 2.创建流对象》 3.打开文件 》 4.写数据 》5.关闭流

#include<fstream>) 》 ofstream ofs;  》 ofs.open("文件路径",打开方式) 》ofs << "132" ; 》ofs.close();

//写文件
void writeFile() {
    ofstream ofs;
    ofs.open("123.txt", ios::out | ios::app);

    char data[100];    

    cout << "Enter your name: ";
    cin.getline(data, 100);
    ofs << data << endl;

    cout << "Enter your age: ";
    cin >> data;
    ofs << data << endl;
    
    ofs << "123456";
    ofs.close();
}
//写文件 (二进制)
void writeBin() {

    class Person {
    public:
        string name;
        int age;
    };
    Person p = {"lwt",30};

    ofstream ofs;
    ofs.open("123.txt",ios::out | ios::binary);

    ofs.write((const char *)&p,sizeof(p));
    ofs.close();

}

 

 

读文件步骤:

1.包含头文件 》 2.创建流对象》 3.打开文件(并判断是否打开成功) 》 4.读数据 》5.关闭流

#include<fstream>) 》 ifstream ifs;  》 ifs.open("文件路径",打开方式) 》四种方式读 》ifs.close();

//读取文件
string getFile() {
    ifstream ifs;
    ifs.open("123.txt", ios::in);

    char data[1024] = { 0 };
    //第一种
    if (ifs.is_open()) {        
        while (ifs >> data) {
            cout << data << endl;
        }    
    }


    //第二种
    while (ifs.getline(data, sizeof(data))) {
        cout << data << endl;
    }


    //第三种 (字符串读)
    string buf;
    while (getline(ifs,buf)) {
        cout << buf << endl;
    }


    //第四种 (一个字符读)
    char c;
    while ((c = ifs.get()) != EOF) { //Een Of File
        cout << c;
    }
    cout << endl;

    ifs.close();

    return "";
}

 

//读文件 (二进制)
void readBin() {

    class Person {
        public:
            char name[20];
            int age;
    };
    Person p ;

    ifstream ifs;
    ifs.open("123.txt", ios::in | ios::binary);
    if (ifs.is_open()) {
        ifs.read((char *)&p, sizeof(Person));

        cout << "姓名:" << p.name <<"年龄:"<< p.age << endl;    
    }
    ifs.close();
}

 

posted @ 2023-11-21 17:02  与f  阅读(13)  评论(0编辑  收藏  举报