c++ 文件io

c++中的文件io,简单的写代码记录下:

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

//往文本文件中写入数据。
void write_content_file() {
    //如果text.txt文件不存在,系统会自动新建一个text.txt文件
    //如果text.txt文件存在了,系统会先把文件清空,除非我们设置了
    //打开文件的属性:ios::app,那么系统就会在文件的末尾追加内容
    ofstream fout("test.txt");
    if (!fout) { cerr << "文件打开失败" << endl; return; }
    //插入一个字符串
    fout << "hello , i am fine." << endl;
    //fout其实就是一个指针,此时,fout它指向了字符串“hello , i am fine.”的末尾。
    //所以当我们希望往文件中插入新的数据时,它就会直接在最后追加。
    int num = 1;
    fout << num << endl;
    fout.close();
}
void read_content_file() {
    //把刚才的内容读取出来
    ifstream fin("test.txt");
    //以读文件为目的打开文件,最容易出现问题
    if (!fin) { cerr << "文件打开失败" << endl; return; }
    //读取一行的方法。
    string str;
    while(getline(fin,str)) {

        if (str.length() > 3) {

            cout << str << endl;
        }else if(str.length()==1){
            cout << "length is 1" << endl;
        }else{

            cout<<"othrer"<<endl;
        }


    }
    fin.close();
}



int main() {

    //write_content_file();
   read_content_file();
    return 0;
}

猜你喜欢

转载自blog.csdn.net/luoyexuge/article/details/80316846