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("写入第二个文件");
}
相关推荐
CYRUS_STUDIO5 分钟前
Frida Hook Native:jobjectArray 参数解析
android·c++·逆向
榆榆欸6 分钟前
4.Socket类、InetAddr类、Epoll类实现模块化
linux·c++·tcp/ip
..过云雨14 分钟前
11. 【C++】模板进阶(函数模板特化、类模板全特化和偏特化、模板的分离编译)
开发语言·c++
予安灵35 分钟前
一文详细讲解Python(详细版一篇学会Python基础和网络安全)
开发语言·python
Lizhihao_44 分钟前
JAVA-堆 和 堆排序
java·开发语言
极客先躯1 小时前
高级java每日一道面试题-2025年3月21日-微服务篇[Nacos篇]-什么是Nacos?
java·开发语言·微服务
BC橡木1 小时前
C++ IO流
c++
try again!1 小时前
rollup.js 和 webpack
开发语言·javascript·webpack
du fei1 小时前
C# 窗体应用(.FET Framework) 线程操作方法
开发语言·c#
du fei1 小时前
C#文件操作
开发语言·c#