I am trying to write a string to a file, but the file contains random codes instead.

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Steve Chang
    New Member
    • Sep 2015
    • 2

    I am trying to write a string to a file, but the file contains random codes instead.

    #include <cstdlib>
    #include <iostream>
    #include <fstream>

    using namespace std;

    int main(int argc, char *argv[])
    {
    ofstream file;
    // string a;
    string a ("file contents\n\0");
    cout<<a<<endl;
    file.open("http ://bytes.com/store.txt",ios: :out);
    file.write((cha r*)&a,sizeof(a) );
    file.flush();
    file.close();
    system("PAUSE") ;
    return EXIT_SUCCESS;
    }
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    This code:

    Code:
    file.write((char*)&a,sizeof(a));
    does not look like the C++ ofstream::write :

    Code:
    ofstream& write (const char* s, streamsize n);
    Your variable a is a string. ofstream::write asks for a const char*. Therefore, supplying the address of a and casting to a char* does not make a into a char* string.

    The string class has a member function c_str() that will covert the string object into a char* string that you can use with ofstream::write .

    Also, sizeof does not give you the size of the string. The actual string may not be inside the string object (then again, it may depending upon the string design). Because of this you use the size() member function to tell you the size of the string.

    Try this:

    Code:
    file.write( a.c_str(),a.size());
    As regards casting in C++, the rule is that unless you are calling aome antique C function with void* arguments, a cast in C++ for other reasons is a design error.
    Last edited by weaknessforcats; Sep 9 '15, 06:43 PM. Reason: added explanation of the string size method.

    Comment

    • Steve Chang
      New Member
      • Sep 2015
      • 2

      #3
      Great! It works perfectly now. Thanks for your prompt help in this matter. Have a great day!

      Comment

      Working...