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

     

  • 相关阅读:
    解决web网页访问慢的问题
    Django安装配置(for Mac)
    Django安装(for Mac)
    HTML5中的新事件
    关于http-equiv
    【转】@fant-face
    textarear中的value....还是...innertext
    清除浮动的元素的margin-top触碰不到,浮动元素的边界
    常用排序算法总结(一)
    JS常用特效方法总结
  • 原文地址:https://www.cnblogs.com/zerotoinfinity/p/12626389.html
Copyright © 2011-2022 走看看