c++ - 在 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 "";
}
你能帮我这里有什么问题以及为什么它不打印吗?
解决方案
您正在尝试将std::string
对象的地址转换为指向char
. 首先,您需要分配足够的大小来读入std::string
- ans.resize(newFile->DEVICE_SIZE);
。其次,您需要char *
从std::string
-获取&ans[0]
。
推荐阅读
- sql-server - 如何从 Excel 工作表定期更新 SQL Server 表
- servicestack - 从 Ormlite 返回自定义对象的值元组
- powershell - 使用 PowerShell 替换文本文件中行中间的字符
- python - 在 pool.map() 和 pool.join() 的上下文中“阻塞”的真正本质是什么?
- c++ - 宏定义中的标记未在此范围内声明
- numpy - Numpy 给出了错误的特征向量?
- c++ - 如何为依赖类型扩展参数包?
- angular - 调用 Firebase 函数会引发错误 - ERROR TypeError: Gb.functions is not a function
- python - PyTorch 循环遍历 epoch,然后输出所有 epoch 的最终值
- html - 带输入字段的中心单选按钮