在 C++ 中使用 read() 从文件中读取
read from file with read() in c++
嗨,我需要做一些类似文件系统的事情,我需要从文件中写入和读取(写入函数工作)我有一个函数签名
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);
。其次,您需要从 std::string
- &ans[0]
.
获取 char *
嗨,我需要做一些类似文件系统的事情,我需要从文件中写入和读取(写入函数工作)我有一个函数签名
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);
。其次,您需要从 std::string
- &ans[0]
.
char *