c++pathname

How to reference a file to be opened in C++ given that its full path name will change from computer to computer?


Our Computer Science teacher has given us a project to make a fully functioning console application using C++. And I have started to make it. But I got stuck at some point. I want to open an editable text (.txt) file using the open() function. But I made a separate folder for all the text files. Usually I have to provide a full directory path in the open() function, which is F:\Work\C++\SchoolProject\TextFiles in my case. But what if I copy the SchoolProject folder in a portable drive and take it to my friend's home and try to run the program in their computer. Will it work? I'm asking because it is not necessary that they will have the Work folder in the F directory or maybe they may not have the F disk at all. So in that case the path will change. So what path I have to type in the open() function so that the program works in each and every computer without changing the address in the open() function every time I try to run the program in some other computer. A source code may be helpful with explanation. Thank You!


Solution

  • Instead of using absolute paths, you should use relative paths. When you run your program from a folder, this is your working path. You can then open files inside this folder or subfolders of this folder by passing only the file name or folder and file name to the open function. So instead of opening C:\... simply open someFolder\someFile.txt.