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

StackOverflow https://stackoverflow.com/questions/19751756

  •  03-07-2022
  •  | 
  •  

Question

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!

Was it helpful?

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.

OTHER TIPS

You could consider having the filename that you parse in as part of a command line argument, like this:

int main(int arg, char* args[]) {

   FILE *newfile = fopen( args[1], "r");

}

You can not be sure all computers have the F: drive mapped correctly so it is better to use Universal Naming Convention (UNC) names i.e. "\server\share\path\file".

A nice way to achieve the same is by using Boost Filesystem, but this makes your code more complicated since you are depending on an external library (read: the students might be confused). The documentation for Boost Filesystem is found here: http://www.boost.org/doc/libs/1_43_0/libs/filesystem/doc/index.htm

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top