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

 

猜你喜欢

转载自www.cnblogs.com/zerotoinfinity/p/12626389.html