Search code examples
c++linuxfilelow-level

read from file with read() in c++


hi i need to do something like filesystem and i need to write and read from file (the write function work) i have a function signature

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

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

and this is my function to read from file and print it

    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 "";
    }

can you help me what is wrong here and why it dosen't print?


Solution

  • You are trying to cast address of std::string object to pointer to char. At first you need to allocate enough size to read into std::string - ans.resize(newFile->DEVICE_SIZE);. Secondly you need to get char * from std::string - &ans[0].