• C++按行读取和写入文件


    按行读取:

    假设有一个文本文件,如下所示:

    1 2 3
    2 3 4
    3 4 5
    5 6 7
    7 8 9

    文件名为split.txt

    目的:按照行读取数据,并一个个的显示出来。

    代码如下:

    #include <iostream>
    #include <sstream>
    #include <fstream>
    #include <string>
    int main(int args, char **argv)
    {
    std::ifstream fin("split.txt", std::ios::in);
    char line[1024]={0};
    std::string x = "";
    std::string y = "";
    std::string z = "";
    while(fin.getline(line, sizeof(line)))
    {
    std::stringstream word(line);
    word >> x;
    word >> y;
    word >> z;
    std::cout << "x: " << x << std::endl;
    std::cout << "y: " << y << std::endl;
    std::cout << "z: " << z << std::endl;
    }
    fin.clear();
    fin.close();
    return 0;
    }

    下面一行一行解读代码:

    首先说明一下头文件,头文件中<iostream>, <string>的作用就不用说了,<fstream>是定义文件的需要的头文件,而<sstream>是字符串流stringstream所需要的头文件。

    第8行: std::ifstream fin("split.txt", std::ios::in); 定义读取的文本文件。

    第9行: char line[1024] = {0}; 用于定义读取一行的文本的变量。

    第10--12行,定义了 x y z 三个字符串变量,用于存放读取一行数据后,分别存放每行的三个数据。

    第13--22行,用一个循环读取每行数据,读取行的函数是getline()函数,然后利用stringstream将每行文本自动按照空格分列,并分别存放到对应的三个字符串变量中。

    23、24行代码,就是刷新缓存,并关闭文件。

    运行结果:

    按行写入:

    目的:向文件中追加文本内容。

    代码如下:

    #include   <iostream> 
    #include   <fstream> 
    #include   <string> 
    using namespace std;
    int main()
    {
    ofstream   ofresult( "result.txt ",ios::app); 
    ofresult<<"123"<<"你是好孩子"<<endl;
    ofresult<<"第二次写文件"<<endl;
    return 0;
    }
  • 相关阅读:
    ThinkCMF框架任意内容包含
    网站防篡改脚本
    Apache Solr Velocity模板远程代码执行
    BurpSuite Intruder模块匹配返回包内容
    Kibana<6.6.0代码执行漏洞复现
    Thinkphp远程代码执行 payload汇总
    常用端口 简洁版
    NISP二级笔记(一) 信息安全管理
    oracle 中的角色
    oracle 用户对象权限
  • 原文地址:https://www.cnblogs.com/DarrenChan/p/7120738.html
Copyright © 2020-2023  润新知