读写文件

1.写文件

#include <fstream>

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;
}

2.读文件

读文件的四种方式,第四种不推荐

#include<iostream>
#include <string>
#include <fstream>

using namespace std;

void test01()
{
    ifstream ifs;
    ifs.open("test.txt", ios::in);
    if (!ifs.is_open())
    {
        cout << "打开失败" << endl;
        return;
    }
    //1
    //char buf[1024] = { 0 };
    //while (ifs >> buf) {
    //    cout << buf << endl;
    //}

    //2
    //char buf[1024] = { 0 };
    //while (ifs.getline(buf, sizeof(buf))) {
    //    cout << buf << endl;
    //}

    //3
    string buf;
    while (getline(ifs, buf)) {
        cout << buf << endl;
    }

    //4
    //char c;
    //while ((c = ifs.get()) != EOF)
    //{
    //    cout << c;
    //}

    ifs.close();
}

int main()
{
    test01();
    system("pause");
    return 0;
}
本文作者:Author:     文章标题:读写文件
本文地址:https://www.ningcaichen.top/archives/166.html     
版权说明:若无注明,本文皆为“宁采晨's Blog”原创,转载请保留文章出处。
Last modification:2020 年 04 月 15 日 16 : 54 PM

Leave a Comment

召唤看板娘