Public Group

# ofstream problem with folders

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

## 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 on other sites

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


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 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 on other sites

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

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

##### Share on other sites

Did you try the following?

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

• 9
• 18
• 29
• 11
• 24