How do you create/open a file (windows)

Hi all,

A very frustrating for me beginner's question:

1
2
3
4
#include <fstream>
std::fstream theDump;
theDump.open("C:\\VP.txt",std::fstream::in | std::fstream::out);
assert(theDump.is_open());


The above code works if I *manually* create a file called "C:\VP.txt". If the file does not exist however, it does not create it, instead it pops the assert! The operating system is windows XP. How should I open my file? I want to write as little code as possible!

Another question: how do I reference the path of my project (VC compiler 2008 express)?

Many thanks!
Last edited on
closed account (S6k9GNh0)
I'm not sure if there is a way to use the STD library to create files, but the windows.h has a couple of prototypes that can create a file for you. One being CreateFile().

http://msdn.microsoft.com/en-us/library/aa363858.aspx
Thanks! Did it as suggested in your link: is there a more civilized (i.e. system independent) way of doing this?
1
2
3
4
5
6
7
8
9
// Note use of forward slash (works even on windows)
char* const dumpFilename = "C:/VP.txt"; 

// Ensure the file exists. EDIT: Oops! This will truncate the file if it exists!!!
std::fstream theDump(dumpFilename, std::fstream::out);

// Re-open for I/O
theDump.close();
theDump.open(dumpFilename);


EDIT: So I guess it doesn't work. Is there some way to do this?
Last edited on
closed account (L3ApX9L8)
You could also use something like
ofstream fileName("C:\\file.txt", ios::app)

The good thing about this is that if it doesnt exist, it will get created. If it exists, the content will get appended (though that might not be what you want, but you can always define a function which deletes the file if the conditions are met...)
Last edited on
I came up with this portable solution.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <fstream>

bool openIO(std::fstream& file, const char* filename) {
    file.open(filename); // Try to open for I/O
    if (!file) {
        file.clear();
        file.open(filename, std::ios::out); // Create using out
        if (!file)  return false;
        file.close();
        file.open(filename); // Open for I/O
        if (!file)  return false;
    }
    return true;
}

int main(){
    std::fstream file;
    if (!openIO(file, "c:/abc.txt")) {
        // couldn't open it
    }
    // ...
}
Last edited on
fstream is apart of std i think.

1
2
3
4
5
6
7
8
9

std::fstream dump("c:\\VP.txt", std::ios::in)
// using out will erase the file everytime you run
// the program (didn't know if you wanted that or not)
if(dump.is_Open())
std::cout<<"FILE IS OPEN"<<std::endl;

dump.close();



Last edited on
Topic archived. No new replies allowed.