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)?
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().
// 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?
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...)
#include <iostream>
#include <fstream>
bool openIO(std::fstream& file, constchar* 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) returnfalse;
file.close();
file.open(filename); // Open for I/O
if (!file) returnfalse;
}
returntrue;
}
int main(){
std::fstream file;
if (!openIO(file, "c:/abc.txt")) {
// couldn't open it
}
// ...
}
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();