ifstream problem

Ok so here is my function to see if file exists and if it does not exist have it create the file. I have read several things online and still can not get this to run correctly. Everything compiles fine but nothing will create the file if file.is_open does not exist. i added the file << "//config file created"; for troubleshooting thinking maybe because i wasn't writing to the file that maybe that caused it not to create one. Still to no avail though. If someone could guide me a little more on what else to check or point out some errors I would be extremely grateful. I sort of think that maybe since it is not a .txt and a .cfg instead that this might be the issue. however the file has to be converted to a .cfg somehow and i can't find any information on that subject.

About the application: It basically checks for a config.cfg file and if it exists later on i will read it and change some values on it via GUI, but if it doesn't exist i need to create it to prevent the rest of my program from crashing. Its for a game called csgo to kind of make editing your cfg files easier and have the ability to apply them in game without having to relaunch every time. I figure this would be a fairly complex thing for my level to write but not out of reach, so it would be a good learning experience while in winter break from school.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
  void read(){
	fstream file;
	file.open("config.cfg", fstream::in);
	if (file.is_open()){
		

		file.close();
		cout << "File read successfully";
	}
	else{
		file.clear();
		file.open("config.cfg");//creates file
		file << "//New config file created." ;
		file.close();
		cout << "File was not found.\n";
		cout << "So we've created one for you!";
	}
	
you have to open it in write-mode (the second time in else)

file.open("config.cfg", fstream::out);
Last edited on
This will test if it exists.

1
2
3
4
5
bool fileExists(const char* _fileName)
{
    std::ifstream fin(_fileName);
    return fin;
}


And this will create a new one

1
2
    std::fstream fhandle;
    fhandle.open("myFile.txt", std::ios::out);


Alternatively, you can use std::ofstream - this is just an example to show that you can create it using fstream::open
Last edited on
@Glandy That makes sense i was thinking that same thought but was unsure on how to implement it. I will give it a try here in a second and let you know how it works out.


@jaded7 That seems a lot more efficient than the way im doing i will try it out as well. If i have some other question on this after messing with it a little more i will let you know.

Thank you for the replies, now i can finally move forward on this project.
Glandy That fixed it. works like a charm now! I'm sure ill hit some other basic problems further down the line in this. Was my first post, i was amazed and happy at how fast and helpful everyone is here.
Topic archived. No new replies allowed.