How can i access the char array inside of an std::string?

Viewed 458

I was given a task to write a file system in Linux that simulates a storage device as a file.

One of the functions I was given needs to read data inside a "file". To do so I have a function that's supposed to return an std::string.

How can I read the data out of the file with the following function directly into an std::string?

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

Is there a way to pass the char array inside of an std::string as a parameter to this function? All of the methods and member functions I have encountered so far only return const char* which doesn't work in this case.

Thanks!

2 Answers

The conventional way of doing this is to pass a pointer to the string’s first character. This is guaranteed to work because the standard guarantees that the characters inside a std::basic_string are stored contiguously ([basic.string]/2).

Thus,

read(addr, str.size(), & str[0]);

works, but only if you have previously resized the string to a non-zero size. Additionally, your read function doesn’t tell you how many characters were read. There needs to be some functionality in your IO API to tell you this.

Actually, it is bad idea to do so, as then std::string class doesn't know, how many characters were inserted. It is much better to create local buffer std::array<char, 256> buf, pass it to function, and then put it into std::string using std::string(buf.data, buf.size()).

Related