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("写入第二个文件");
}
相关推荐
serve the people7 分钟前
解决osx-arm64平台上conda默认源没有提供 python=3.7 的官方编译版本的问题
开发语言·python·conda
柒七爱吃麻辣烫33 分钟前
在Linux中安装JDK并且搭建Java环境
java·linux·开发语言
fallzzzzz33 分钟前
C++ stl中的list的相关函数用法
c++·list
极小狐44 分钟前
如何构建容器镜像并将其推送到极狐GitLab容器镜像库?
开发语言·数据库·机器学习·gitlab·ruby
多多*1 小时前
Java反射 八股版
java·开发语言·hive·python·sql·log4j·mybatis
正在走向自律1 小时前
从0到1:Python机器学习实战全攻略(8/10)
开发语言·python·机器学习
悦悦子a啊2 小时前
PTA:jmu-ds-最短路径
c++·算法·图论
FY_20182 小时前
键盘输出希腊字符方法
开发语言
西西弗Sisyphus2 小时前
Python 处理图像并生成 JSONL 元数据文件 - 灵活text版本
开发语言·python
小王努力学编程2 小时前
高并发内存池(三):TLS无锁访问以及Central Cache结构设计
jvm·数据结构·c++·学习