I have a simple problem to do a fwrite, and I don't know why.
I have :
std::string maLigne;
fwrite(maLigne, sizeof(maLigne), 1, fichierEcrit);
That returns me :
invalid cast from type 'std::string {aka std::basic_string<char>}' to type 'void*'
I try :
fwrite(&maLigne, sizeof(maLigne), 1, fichierEcrit);
But there's nothing in the file, so I guess it's wrong.
Why is this not working ?
It is not working because you are trying to use a low-level C function to write to a file a C++ object.
If you want to use the C fwrite
function, yo have to pass as parameter the pointer to the memory where the data is, the size of each element, the number of elements and the file handle. maLigne
is an stack-based object, not a pointer. &maLigne
is the address of that object, but not the address where the data string is (which is located in the heap). sizeof(maLigne)
is the size of the object in the stack (always the same, typically as two pointers size, regardless of the contained data), but not the string length.
That is what is wrong.
So, you need to know the pointer where the string is located (c_str()
function member), the element size (sizeof(char)
, since the string
class works with char
) and the number of elements (the string length: size()
member function).
But better to use C style function, it would be preferable use I/O C++ functions:
std::ofstream fichierEcrit("my_file_name");
std::string maLigne;
fichierEcrit << maLigne;
And you have not be aware about buffers and size, since the operator <<
on the stream object (fichierEcrit
) and the string object (maLigne
) manages that for you.