C++ 文件操作

头文件:#include<fstream>

写文件对象:ofstream

读文件对象:ifstream

读写对象:fstream

分清楚两个 <<表示写入 >>表示读取

cpp 复制代码
#include <iostream>
#include <fstream>

void writeFile()
{
    std::ofstream file;
    file.open("1.txt", std::ios::app);

    // std::ofstream file("1.txt", std::ios::app)  上面两行代替
    if (file.is_open())
    {
        file << "你好世界" << std::endl;
    }
    file.close();
}
void readFile()
{
    std::ifstream file;
    file.open("1.txt");

    // std::ifstream file("1.txt"); 上面liang
    std::string _str;
    if (file.is_open())
    {
        while (getline(file, _str)) // 读取一行
        {
            std::cout << _str << std::endl;
        }
    }
}

void readWriteFile()
{
    std::fstream file;
    file.open("mytext.text", std::ios::app);
    if (file.is_open())
    {
        file << "笑鼠啦" << std::endl;           // 写文件
        file << "祝我通过金山面试" << std::endl; // 写文件
        file.close();

        // 读文件
        file.open("mytext.text");
        std::string str;
        while (getline(file, str))
        {
            std::cout << str << std::endl;
        }
    }
    file.close();
}
int main()
{
    readWriteFile();
    return 0;
}

对于权限如下:

案例(日志文件滚动落盘,限制1G):

cpp 复制代码
#include <iostream>
#include <fstream>
#include <string>
#include <queue>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <atomic>
#include <filesystem>

class AsyncLogger
{
public:
    AsyncLogger(const std::string &baseFileName) : baseFileName_(baseFileName), currentFileNamber_(0), stop_(false)
    {
        openNameFile();                                            // 创建文件
        writeThread_ = std::thread(&AsyncLogger::writeLoop, this); // 开启异步日志线程
    }
    ~AsyncLogger()
    {
        {
            std::unique_lock<std::mutex> lock(mutex_);
            stop_ = true;
        }
        cv_.notify_one();
        if (writeThread_.joinable())
        {
            writeThread_.join();
        }
    }

    // 写日志接口
    void log(const std::string &message)
    {
        std::unique_lock<std::mutex> lock(mutex_);
        logQueue_.push(message);
        cv_.notify_one();
    }

private:
    // 日志线程
    void writeLoop()
    {
        std::queue<std::string> localQueue;
        while (true)
        {
            {
                std::unique_lock<std::mutex> lock(mutex_);
                cv_.wait(lock, [this]()
                         { return stop_ || !logQueue_.empty(); }); // 条件变量日志队列不为空
                // 关闭
                if (stop_ && logQueue_.empty())
                {
                    break;
                }
                // 交换到临时队列
                localQueue.swap(logQueue_);
            }

            // 写入到文件
            while (!localQueue.empty())
            {
                const std::string &message = localQueue.front();
                logFile_ << message << std::endl;
                // 超出一个G,创建新文件
                if (logFile_.tellp() > 1LL * 1024 * 1024 * 1024)
                { // 文件字节为单位
                    logFile_.close();
                    openNameFile();
                }
                localQueue.pop();
            }
            // 刷新缓存
            logFile_.flush();
        }
    }
    // 打开文件
    void openNameFile()
    {
        std::string fileName = baseFileName_ + std::to_string(currentFileNamber_++) + ".log";
        logFile_.open(fileName, std::ios::app);
        if (!logFile_.is_open())
        {
            std::cerr << "文件打开失败" << std::endl;
        }
    };

    std::string baseFileName_;
    int currentFileNamber_;
    std::ofstream logFile_;            // 文件写入对象
    std::queue<std::string> logQueue_; // 日志队列
    std::mutex mutex_;
    std::condition_variable cv_;
    std::thread writeThread_; // 日志线程
    std::atomic<bool> stop_;
};

int main()
{
    AsyncLogger logger("mylog");
    logger.log("这是一个异步日志系统");
    logger.log("写入第二个文件");
}
相关推荐
future141224 分钟前
C#学习日记
开发语言·学习·c#
码农编程录30 分钟前
【c/c++3】类和对象,vector容器,类继承和多态,systemd,std&boost
c++
king_harry40 分钟前
Java程序-OceanBase Connector/J 示例
开发语言
傻啦嘿哟1 小时前
Python 办公实战:用 python-docx 自动生成 Word 文档
开发语言·c#
翻滚吧键盘2 小时前
js代码09
开发语言·javascript·ecmascript
q567315232 小时前
R语言初学者爬虫简单模板
开发语言·爬虫·r语言·iphone
??tobenewyorker2 小时前
力扣打卡第二十一天 中后遍历+中前遍历 构造二叉树
数据结构·c++·算法·leetcode
rzl022 小时前
java web5(黑马)
java·开发语言·前端
时序数据说2 小时前
为什么时序数据库IoTDB选择Java作为开发语言
java·大数据·开发语言·数据库·物联网·时序数据库·iotdb
jingling5553 小时前
面试版-前端开发核心知识
开发语言·前端·javascript·vue.js·面试·前端框架