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, "\n");
            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();
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM