Hello, I'm working with files in a C++ project AND the text file that I need to open is in the same directory, however when just trying to open it like this:

string inputFile = "myText.txt";

It will not open, even though it's in the same directory, so then I have to put the file location (the directory path) which is fine BUT other people will be using this application and won't have access to my directory..

I want something that shows the current directory, like in C# there's a function for this.. I can't seem to find the same one in C++ so I've been working with this:

#include <stdio.h>
#include <dirent.h>
#include <iostream>
using namespace std;

int main (int c, char *v[]) {
 	
     DIR * mydir = opendir(".");

    cout << mydir;
    return 0;
}

But it just shows me the memory location, even if I have &mydir

Any suggestions? =)

Hey thanks for the reply..

I have this now basically:

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string>

using namespace std;
string CurrentPath;

string getCurrentPath();
 
int main(int argc, char** argv)
{
	cout << getCurrentPath();
	   return 0;
}
string getCurrentPath()
{
	size_t size;
		char *path=NULL;
	path=getcwd(path,size);
	CurrentPath=path;
	return path;
}

But when I run the program and output it, the output isn't displaying the file path to where the location is, just showing like:

/Users/[my_computer_name]

Any ideas?

Step through this and see what happens:

#include <direct.h>

int main(void)
{
   char strDir[129] = {0};
   puts(_getcwd(strDir, 128));
   puts(strDir);
   return 0;
}

...depending on OS (Windows)

Also consider this:

#ifdef WINDOWS
      #include <direct.h>
      #define GetCurrentDir _getcwd
#else
     #include <unistd.h>
     #define GetCurrentDir getcwd
#endif

...which I saw on this post:

Edited 4 Years Ago by thines01: clarity

Comments
Great help - Thanks!

getcwd() returns the current working directory. That's the directory to which you can expect relative paths to resolve. Thus, it certainly explains why your relative path isn't finding the file if the current working directory is different. An easy solution would be using chdir() to force the current directory you want rather than using whatever happens to be the default.

This question has already been answered. Start a new discussion instead.