【问题标题】:read from file with read() in c++在 C++ 中使用 read() 从文件中读取
【发布时间】:2020-03-28 13:20:41
【问题描述】:

嗨,我需要做一些类似文件系统的事情,我需要从文件中读写(写函数工作)我有一个函数签名

void read(int addr, int size, char *ans);

void BlockDeviceSimulator::read(int addr, int size, char *ans) {
    memcpy(ans, filemap + addr, size);
}

这是我从文件中读取并打印它的功能

    std::string MyFs::get_content(std::string path_str) {

        std::string ans;
//open file
        BlockDeviceSimulator *newFile = new BlockDeviceSimulator(path_str);
        newFile->read(1,newFile->DEVICE_SIZE,(char*)&ans);
        std::cout << ans << std::endl;
        delete newFile;
        return "";
    }

你能帮我这里出了什么问题以及为什么它不打印吗?

【问题讨论】:

标签: c++ linux file low-level


【解决方案1】:

您正在尝试将std::string 对象的地址转换为指向char 的指针。首先,您需要分配足够的大小来读入std::string - ans.resize(newFile-&gt;DEVICE_SIZE);。其次,您需要从std::string - &amp;ans[0] 获取char *

【讨论】:

  • a1ezh 和@d.z:std::string 具有获取内部缓冲区地址的功能:.data()。这比&amp;ans[0] 更惯用,尽管C++11 确实为[0, size()] 中的每个i 定义了data() + i == std::addressof(operator[](i)),因此这在C++11 中是安全的。我不确定&amp;ans[0] 在早期的 C++ 中是否安全。例如我认为它可能会破坏一个较旧的 std::string ,它仅在您调用非 const .data() 时才会执行懒惰的写时复制。
  • @PeterCordes data()(与 c_str() 一样)在 C++11 和 CharT* 中返回 const CharT*,仅从 C++17 开始(仅 data())。因此reference operator[] 更通用。最好在 C++11 之前使用std::vector&lt;char&gt;。它保证是连续的。
  • @a1ezh:啊,你是对的。在该 cppreference 页面中仅提及某些重载为 const 仅适用于 C++17。但是operator[] is also UB in C++11 and later对于第一个(非常量)版本,如果将此字符修改为除CharT() 以外的任何值,并且 C++20 将其更改为返回 @ 987654345@参考
  • 我猜你应该读入其他缓冲区,然后使用std::string::replace 或构造函数。这涉及两倍的内存,意味着您需要以某种方式分配另一个缓冲区,但.resize() 在 read() 调用之前仍然会浪费时间将内存归零。我讨厌 C++ std::vector 和 st::string 很难为read() 类似的系统调用和函数分配缓冲区而不浪费时间对其进行零初始化。就像有效使用它们的唯一方法一样,如果所有内容都使用 .push_back 而不是传递指针+长度。
猜你喜欢
  • 1970-01-01
  • 2013-11-15
  • 1970-01-01
  • 2022-01-09
  • 1970-01-01
  • 2011-08-25
  • 2014-11-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多