c++ - ofstream 写入十六进制而不是 char*

标签 c++ file ofstream

我尝试编写一个简单的记录器,但 ofstream 将十六进制而不是字符写入文件。 定义:

#pragma once
#include <iostream>
#include <fstream>
#include <string>
#define LOG Logger::getInstance()
class Logger
{
public:
    static Logger m_instance;
    static Logger &getInstance()
    {
        if (m_logfile == nullptr)
        {
            m_logfile = new std::ofstream(m_logfile_string.c_str(),
                                          std::ofstream::out | std::ofstream::app);
        }
        return m_instance;
    }

    Logger &operator<<(const std::string &c);
    Logger &operator<<(const char c[]);

private:
    static std::ofstream *m_logfile;
    static std::string m_logfile_string;
    Logger() {};
    Logger(const Logger &) = delete;
    Logger(Logger &&other) = delete;
    Logger &operator=(const Logger &other) = delete;
    Logger &operator=(Logger &&other) = delete;

    ~Logger()
    {
        if (m_logfile != nullptr)
            m_logfile->close();
    };

    std::string currentDateTime() const;
};

实现。

#include "Logger.h"
#include <iostream>
#include <ctime>

Logger Logger::m_instance;
std::ofstream *Logger::m_logfile = nullptr;
std::string Logger::m_logfile_string = "log.txt";

Logger &Logger::operator<<(const std::string &c)
{
    this->operator<<(c.c_str());
    return *this;
}

Logger &Logger::operator<<(const char c[])
{
    std::cout << currentDateTime() << " - "
              << c << std::endl;
    m_logfile->operator<<(c);
    return *this;
}

// Get current date/time, format is YYYY-MM-DD.HH:mm:ss
std::string Logger::currentDateTime() const
{
    auto now = time(nullptr);
    struct tm  tstruct;
    char       buf[80];
    tstruct = *localtime(&now);
    strftime(buf, sizeof(buf), "%Y-%m-%d.%X", &tstruct);

    return buf;
}

用法:

#include "Logger.h"
void main()
{
    LOG << "started"; // Logger::getInstance() << "started";
}

结果: log.txt中的00007FF696EF3C00控制台输出是正确的。

这里出了什么问题?

最佳答案

您使用 iostream 的成员函数:

m_logfile->operator<<(c);

没有成员函数operator<<(char* c) ,但是有operator<<(void* p) ,因此指针被隐式转换。请参阅有关 ostream 的文档。

char* 的运算符不是类成员函数:

 ostream& operator<< (ostream& os, const char* s);

请参见此处:operator<< (ostream)

所以你需要这段代码:

operator<<(*m_logfile, c);

或者更干净:

(*m_logfile) << c;

测试示例:

#include <iostream>

int main() {
    std::cout.operator<<("test");
    operator<<(std::cout, "test");
    std::cout << "test";
}

打印 0x400944testtest .

关于c++ - ofstream 写入十六进制而不是 char*,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30233986/

相关文章:

已作为非阻塞打开的管道上的 Python readline

c++ - std::ofstream 是可移动的吗?

c++ - 在 C++ 中删除 ofstream 中的一行

c++ - 离开类文件时变量重置

c++ - 我无法让非常基本的命令提示 rune 本处理器正常工作。 ofstream() 的问题

php - hash_djb2 PHP 结果错误?

c++ - 暂停程序直到 ofstream::flush() 完成

c++ - 关于对象的复制

java - 创建流时是否应该显式创建文件?

c - 获取文件名分隔的c - linux