ofstream problem with folders

Started by
5 comments, last by swiftcoder 10 years, 8 months ago

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;
}


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.

My Oculus Rift Game: RaiderV

My Android VR games: Time-Rider& Dozer Driver

My browser game: Vitrage - A game of stained glass

My android games : Enemies of the Crown & Killer Bees

\ 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.

"Most people think, great God will come from the sky, take away everything, and make everybody feel high" - Bob Marley

I tries \\ and / but now it doesn't open my file. huh.png

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".

"Most people think, great God will come from the sky, take away everything, and make everybody feel high" - Bob Marley

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

Did you try the following?


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

Tristam MacDonald. Ex-BigTech Software Engineer. Future farmer. [https://trist.am]

This topic is closed to new replies.

Advertisement