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? =)

5 Years
Discussion Span
Last Post by Narue

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


Any ideas?


Step through this and see what happens:

#include <direct.h>

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

...depending on OS (Windows)

Also consider this:

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

...which I saw on this post:

Edited by thines01: clarity

Votes + 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.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.