Thread: Write to File in nonexistent path

  1. #1
    Registered User
    Join Date
    Jan 2009
    Posts
    159

    Write to File in nonexistent path

    Hi,
    I just found that if I use fstream to write to a file under nonexistent directory, it will not report any error or do any thing you want during execution. For example, where there is no directory called "tmp" under current directory,
    Code:
    #include <fstream>
    
    using namespace std;
    
    int main()
    {
        ofstream fout( "./tmp/results.txt", ios::app );
        fout << 2 <<endl;
        return 0;
    }
    How to specify in code to create a directory if it is not existent ? Thanks!

  2. #2
    Officially An Architect brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,396
    Quote Originally Posted by lehe View Post
    How to specify in code to create a directory if it is not existent ? Thanks!
    Forget creating the directory, how do you determine if you need to create it? The answer is, it's not portable. The closest thing to a portable method is stat(), and that's only UNIX-portable.
    Code:
    //try
    //{
    	if (a) do { f( b); } while(1);
    	else   do { f(!b); } while(1);
    //}

  3. #3
    Registered User
    Join Date
    Jan 2009
    Posts
    159
    Thanks!
    So testing if a directory exists is also system-dependent? In Linux, how to make fstream to report if the directory it tries to write in does not exist, and to make one?

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Data Structure Eror
    By prominababy in forum C Programming
    Replies: 3
    Last Post: 01-06-2009, 09:35 AM
  2. How to write in a file using fscanf and fprintf
    By g_p in forum C Programming
    Replies: 8
    Last Post: 05-24-2007, 01:52 PM
  3. Game Pointer Trouble?
    By Drahcir in forum C Programming
    Replies: 8
    Last Post: 02-04-2006, 02:53 AM
  4. Simple File encryption
    By caroundw5h in forum C Programming
    Replies: 2
    Last Post: 10-13-2004, 10:51 PM
  5. Hmm....help me take a look at this: File Encryptor
    By heljy in forum C Programming
    Replies: 3
    Last Post: 03-23-2002, 10:57 AM