首页 > 解决方案 > 在 C++ 中使用 read() 从文件中读取

问题描述

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

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++linuxfilelow-level

解决方案


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


推荐阅读