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("写入第二个文件");
}
相关推荐
辰阳星宇7 分钟前
203、【数组】NLP分词实现(Python)
开发语言·python
-拟墨画扇-28 分钟前
C++ | 面向对象 | 继承
c++·向上转型·虚继承
Y_3_71 小时前
30 分钟从零开始入门 CSS
开发语言·前端·css·人工智能·python·tensorflow
tianmu_sama1 小时前
[Linux高性能服务器编程] 多线程编程
linux·服务器·c++·算法
挨代码1 小时前
UE_C++ —— Gameplay Tags
c++·ue
敢嗣先锋2 小时前
鸿蒙5.0实战案例:基于WaterFlow的页面滑动加载
c++·移动开发·harmonyos·arkui·组件化·鸿蒙开发·页面布局
weixin_399264292 小时前
QT C++ QtConcurrent::run 异步任务 简单例子
开发语言·c++
御风@户外2 小时前
qt5的中文乱码问题,QString、QStringLiteral 为 UTF-16 编码
c++·qt·乱码
JKHaaa2 小时前
单链表的排序(C++)
数据结构·c++·算法
东方忘忧2 小时前
QT MD5校验文件和数据的完整性
开发语言·qt