c++ - Simple FWrite that goes wrong -



c++ - Simple FWrite that goes wrong -

i have simple problem fwrite, , don't know why.

i have :

std::string maligne; fwrite(maligne, sizeof(maligne), 1, fichierecrit);

that returns me :

invalid cast type 'std::string {aka std::basic_string<char>}' type 'void*'

i seek :

fwrite(&maligne, sizeof(maligne), 1, fichierecrit);

but there's nil in file, guess it's wrong.

why not working ?

it not working because trying utilize low-level c function write file c++ object.

if want utilize c fwrite function, yo have pass parameter pointer memory info is, size of each element, number of elements , file handle. maligne stack-based object, not pointer. &maligne address of object, not address info string (which located in heap). sizeof(maligne) size of object in stack (always same, typically 2 pointers size, regardless of contained data), not string length.

that wrong.

so, need know pointer string located (c_str() function member), element size (sizeof(char), since string class works char) , number of elements (the string length: size() fellow member function).

but improve utilize c style function, preferable utilize i/o c++ functions:

std::ofstream fichierecrit("my_file_name"); std::string maligne; fichierecrit << maligne;

and have not aware buffers , size, since operator << on stream object (fichierecrit) , string object (maligne) manages you.

c++ fwrite

Comments

Popular posts from this blog

model view controller - MVC Rails Planning -

ruby on rails - Devise Logout Error in RoR -

html - Submenu setup with jquery and effect 'fold' -