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("写入第二个文件");
}
相关推荐
jojo_zjx4 小时前
GESP 24年12月2级 数位和
c++
自由的好好干活4 小时前
PCI9x5x驱动移植支持PCI9054在win7下使用3
c++·驱动开发
techdashen4 小时前
Rust OnceCell 深度解析:延迟初始化的优雅解决方案
开发语言·oracle·rust
少控科技4 小时前
QT新手日记033
开发语言·qt
王九思4 小时前
Java 内存分析工具 MAT
java·开发语言·安全
superman超哥5 小时前
Serde 的零成本抽象设计:深入理解 Rust 序列化框架的哲学
开发语言·rust·开发工具·编程语言·rust序列化
夕除5 小时前
java--2
java·开发语言
星辰徐哥5 小时前
Rust函数与流程控制——构建逻辑清晰的系统级程序
开发语言·后端·rust
liliangcsdn5 小时前
如何使用lambda对python列表进行排序
开发语言·python
WBluuue6 小时前
数据结构与算法:dp优化——优化尝试和状态设计
c++·算法·leetcode·动态规划