zoukankan      html  css  js  c++  java
  • C++读写txt

    1、File*

    (1) 写入txt

    void WriteTXT()
    {
        std::string filepath;
        FILE* file = fopen(filepath.c_str(), "wt+");
        if (file) 
        {
            std::string str = "test";
            std::stringstream ss;
            ss << "write txt  " << str;
            fputs(ss.str().c_str(), file);
            fclose(file);
        }
    }

    (2) 按行读取txt

    void ReadTXT()
    {
        std::string filePath;
        FILE* file = fopen(filePath.c_str(), "r");
        if (file)
        {
            char buff[1000];
            while(fgets(buff, 1000 ,file) != NULL)
            {
                char *pstr = strtok(buff, "
    ");
                if (pstr)
                {
                    std::string str = pstr;
                }
            }
            fclose(file);
        }
    }

     2、ifstream、ofstream

    (1) 文件打开方式

    ios::in 读文件打开
    ios::out 写文件打开
    ios::ate 从文件尾打开
    ios::app 追加方式打开
    ios::binary 二进制方式打开
    ios::trunc 打开一个文件时,清空其内容
    ios::nocrate 打开一个文件时,如果文件不存在,不创建
     ios::noreplace  打开一个文件时,如果文件不存在,创建该文件 

    (2) 写入txt

    #include <fstream>
    void WriteTXT()
    {
        ofstream ofs;
        ofs.open("text.txt", ios::out);
        ofs << "write message" << endl;
        ofs.close();
    }

    (3) 读取txt

    #include <fstream>
    void ReadTXT()
    {
        ifstream ifs;
        ifs.open("text.txt", ios::in);
        if (!ifs.is_open()) {
            cout << "文件打开失败!" << endl;
            return;
        }
        // 方式一
        char buf[1024] = { 0 };
        while (ifs >> buf) {
            cout << buf << endl;
        }
        // 方式二
        char buf[1024];
        while (ifs.getline(buf, sizeof(buf))) {
            cout << buf << endl;
        }
        // 方式三
        string buf;
        while (getline(ifs, buf)) {
            cout << buf << endl;
        }
        // 方式四,不推荐用
        char c;
        while ((c=ifs.get()) != EOF) {
            cout << c;
        }
        ifs.close();
    }

     

  • 相关阅读:
    apache伪静态设置
    ZeroClipboard.js兼容各种浏览器复制到剪切板上
    table 如何给tr border颜色
    JSON用法之将PHP数组转JS数组,JS如何接收PHP数组
    jquery操作select(增加,删除,清空)
    JS生成随机的由字母数字组合的字符串
    Redis连接(二)
    Redis集群(一)
    wap启用宏
    windows 10激活
  • 原文地址:https://www.cnblogs.com/zerotoinfinity/p/12626389.html
Copyright © 2011-2022 走看看