Jump to content
  • Advertisement
Sign in to follow this  
GungHo88

ofstream problem with folders

This topic is 1886 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Ello. This code is not working as intended. I have my exe and in the same folder I have an inventories folder with text files. This code won't open inventories\Noa.txt. It creates a file called inventoriesNoa.txt in the same folder as my cpp files. I want it to properly navigate to the inventories\Noa.txt file and search in the same directory the exe is in. How do I do this?

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

using namespace std;

int main()
{
	
	ofstream out;
	
	out.open("\inventories\Noa.txt");

	if (!out.is_open())
	{
		cout << "The file could not be opened";
	}

	out << "hi";

	getch();
	return 0;
}


Edited by GungHo88

Share this post


Link to post
Share on other sites
Advertisement

Short answer: Change all of your \ to \\

out.open("\\inventories\\Noa.txt");

Longer Answer:

In most programning languages, when you write a \ inside a string it means: the next letter is special.

For example "\n" is newline (Enter).

So "\i" is treated as a special letter.

" \" " is a quote (how else would you put the quote character inside a string?)

To tell the compiler that you want the \ to be only a "\" you need to double it: First backslash tells the compiler you want a special character, the second one tells the compiler that the special character you want is a slash.

Edited by SillyCow

Share this post


Link to post
Share on other sites

\ is the escape character in strings, if you want a backslash use \\

 

/ will work though since the C libraries convert it to the correct directory separator, use that instead.

Share this post


Link to post
Share on other sites

If it is relative to the same directory use "./directoryname/pathname/filename.extension", starting with a \\ or / means "start from the root directory of the drive containing the working directory".

Share this post


Link to post
Share on other sites

If it is relative to the same directory use "./directoryname/pathname/filename.extension", starting with a \\ or / means "start from the root directory of the drive containing the working directory".

 

Can you post a working example. It's still not working.  ohmy.png

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!