Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/linux/28.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 用c+;中的read()从文件中读取+;_C++_Linux_File_Low Level - Fatal编程技术网

C++ 用c+;中的read()从文件中读取+;

C++ 用c+;中的read()从文件中读取+;,c++,linux,file,low-level,C++,Linux,File,Low Level,嗨,我需要做一些类似文件系统的事情,我需要从文件中写和读(写函数工作),我有一个函数签名 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::

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

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 MyFs::get_content(std::string path_str){
std::字符串ans;
//打开文件
BlockDeviceSimulator*newFile=新BlockDeviceSimulator(路径_str);
新建文件->读取(1,新建文件->设备大小,(字符*)&ans);

std::cout您正试图将
std::string
对象的地址强制转换为指向
char
的指针。首先,您需要分配足够的大小来读取
std::string
-
ans.resize(newFile->DEVICE_size);
。其次,您需要从
std::string
-
ans[0]获取
char

ans.c_str()
似乎合适。这是否回答了您的问题?否,因为我认为错误在于我调用读取地址,但我不知道如何修复ita1ezh,@d.z:std::string有一个获取内部缓冲区地址的函数:。这比
&ans[0]更惯用
,虽然C++11确实为
[0,size()]
中的每个i定义了
data()+i==std::addressof(运算符[](i))
,但这在C++11中是安全的。我不确定
&ans[0]在早期C++中,甚至是安全的;例如,我认为它可能会在只调用非const <代码> > DATA()(/COD>)时,在写时做惰性拷贝:“PTER CORDES <代码>数据())/>(如As>代码> CyString()/Case>返回C++ >代码>*/C> > C++ 11和<代码>图表*<代码>,因为C++ 17(仅<代码>数据())/>代码>。因此,
reference操作符[]
更通用。最好在C++11之前的版本中使用
std::vector
。它保证是顺序的。@a1ezh:啊,你说得对。在cppreference页中只提到一些重载是常量,这只适用于C++17。但是:第一个(非常量)版本,如果将此字符修改为除
CharT()以外的任何值,则行为未定义
和C++20将其更改为返回一个
constepr
引用我猜您应该读入其他缓冲区,然后使用
std::string::replace
或构造函数。这会占用两倍的内存,意味着您需要以某种方式分配另一个缓冲区,但
.resize()在读()调用之前,仍然浪费时间重置内存。我讨厌C++ STD::vector和S::string使得分配给<代码>()的缓冲区是如此困难。
-喜欢系统调用和函数而不浪费时间零初始化它。喜欢有效使用它们的唯一方法是使用
。向后推,而不是传递指针+长度。