CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3

Thread: file creation

  1. #1
    Join Date
    Apr 2003
    Location
    Bangalore
    Posts
    38

    file creation

    Hi

    in my application i want to read data from file and incase file doesnot exist then new file has to be created and some default values r written to file.


    my doubt is when i use

    #include<iostream.h>
    #include<fstream.h>

    it is working properly.


    but now i changed to

    #include<iostream>
    #include<fstream>
    using namespace std;

    and it is not creating file when doesnot exist.


    the file modes that i have taken are
    fstream file;
    file.open("cache.txt",ios::in | ios::ate | ios:ut);

    can any one try this out..

    bye
    seshu
    Last edited by seshreddy; May 1st, 2003 at 10:49 PM.
    make it possible

  2. #2
    Join Date
    Aug 2000
    Location
    West Virginia
    Posts
    7,725
    I seem to remember that the open modes act differently,
    but I don't have any documentation in front of me (or
    even remember where I saw it ... maybe it was in
    a some other codeguru thread).

    I think that this work-around does what you want ...

    Code:
    #include <fstream>
    #include <iostream>
    
    using namespace std;
    
    void MyOpenFile(std::fstream& file, const char* fname)
    {
        file.open(fname,std::ios::in);
    
        if (!file.is_open())
        {
            // file does not exist, create it;
            file.close();
            file.open(fname,ios::out);
        }
    
        // close file and open the way we really want ...
        file.close();
        file.clear();
        file.open(fname,ios::in | ios::ate | ios::out);
    }
    
    
    int main()
    {
        fstream file;
        MyOpenFile(file,"cache.txt");
    
        file << "hello" << endl;
    
    
        return 0;
    }

  3. #3
    Join Date
    Apr 2003
    Location
    Bangalore
    Posts
    38
    Hi Philip Nicoletti

    as u told is work-around only. but we could not find the actual reason.

    thank u.

    at least u have given me one solution.

    when see ur idea though i know that "in"mode is working properly why i did not think like u.


    okey bye

    seshu
    make it possible

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