zoukankan      html  css  js  c++  java
  • 【C++】文件读写

    这只是记录自己的实践,有关文件流的详细、完整说明请参考其他网络资源或者c++操作手册。
    相似的博客内容多了不是一件好事,这会让我们寻找有用信息的时候变长,but,为了记录,我还是写一写自己遇到的吧


    读写文件应该有的流程

    读文件

    首先要包含头文件:

    #include <fstream>

    然后定义文件流对象:

    string dataFile = "yourData.txt";
    fstream foi(dataFile);

    最好判断一个文件是否打开:

        if (!foi.is_open())
        {
            //推荐用cerr,不用cout
            cerr << "file is not open!" << endl;
        }

    接下来自然就是读取文件里面的数据到变量,然后处理,你这样:

        for (int i = 0; i < num; i++)
        {
            foi >> data1[i] >> data2[i] >> data3[i];
        }
        //对数据进行相应处理
        ......

    最后关闭文件流:

    foi.close();

    写文件

    写文件与读文件基本一样,不一样的是”<<”与”>>”:

        fstream fout("out.txt", ios::out);
        for (int i = 0; i < cycleNum; i++)
        {
            fout << data1[i] << "	" << data2[i] << "	" << data3[i] << "	" << endl;
        }
        fout.close();
  • 相关阅读:
    ssh实现免密码登录和文件传输
    linux后台执行程序相关命令
    orchestrator
    curl下载安装与使用
    goland使用
    mysql集群
    consul理解
    my.cnf
    数据库的表设计
    项目常见面试问题
  • 原文地址:https://www.cnblogs.com/shanchuan/p/8150339.html
Copyright © 2011-2022 走看看