CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    Mar 2009
    Posts
    3

    Question unable to write to a text file using VC++, newbie question

    Hi all

    This is my first post in this forum.

    Im a student learning C++ and i have run into a wall when trying to write to a text file.

    its a simple code but seems that it has issues. can anyone take a look at it and tell me what i have done wrong?

    Code:
     
    #include <iostream> 
    #include <fstream> 
    using namespace std; 
    
    
    int main() 
    { 
      ofstream out("C:\Users\Me\Documents\Visual Studio 2008\Projects\filewrite\test.txt"); 
      if(!out) { 
        cout << "Cannot open file.\n"; 
        return 1; 
       } 
     
      out << 10 << " " << 123.23 << endl; 
      out << "This is a short text file."; 
     
      out.close(); 
     
      return 0; 
    }


    I have created a textfile called test.txt in the folder specified above. do i have to do some project properties changing in VS2008 too?

    cos when i run the program it says the following.

    "cannot open file"



    thanks


    PS: i have tried many other writing to file codes i have found online and they give similar errors.

  2. #2
    Join Date
    Jan 2002
    Location
    Houston, TX
    Posts
    1,421

    Re: unable to write to a text file using VC++, newbie question

    In a literal string, you need to escape the backslash character.
    Code:
      ofstream out("C:\\Users\\Me\\Documents\\Visual Studio 2008\\Projects\\filewrite\\test.txt");
    Hope that helps.
    Be sure to rate those who help!
    -------------------------------------------------------------
    Karl - WK5M
    PP-ASEL-IA (N43CS)
    PGP Key: 0xDB02E193
    PGP Key Fingerprint: 8F06 5A2E 2735 892B 821C 871A 0411 94EA DB02 E193

  3. #3
    Join Date
    Mar 2009
    Posts
    3

    Smile Re: unable to write to a text file using VC++, newbie question

    thank you so much! it solved the problem!


    wow, i wasted hours trying to figure that out!

  4. #4
    Join Date
    Sep 2004
    Location
    Holland (land of the dope)
    Posts
    4,123

    Re: unable to write to a text file using VC++, newbie question

    This explains your problem

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured