-2

I have built a program in c++ whitch checks how many words a text has. The text is stored in a .txt file in the same directory as my .exe file. I was wondering if there is a way to make the name of my .txt file irrelevant as long as the .txt file is in the same directory as my .exe file is? I would like to be able to change the name of the .txt file and still run my program successfully without getting a "error opening file" message.

  • You have two problems: The first is that there's no *standard* way to list contents of directories in C++ ([at least not yet](http://en.cppreference.com/w/cpp/filesystem)). You have to use operating-system functions for that. The second problem is that your directory isn't really known either. [There might operating-system specific functions to get that as well though](http://stackoverflow.com/questions/1528298/get-path-of-executable). – Some programmer dude Aug 01 '16 at 23:17
  • @DimChtz: There is no standard API for getting the executable path of the calling process (unless you count `argv[0]`, but that only applies to console apps, and it can lie). – Remy Lebeau Aug 01 '16 at 23:24
  • 3
    What happens when there's two or more text files in that directory? Maybe you should require the filename to be passed on the command line. – Retired Ninja Aug 01 '16 at 23:24

1 Answers1

0

You need to enumerate the files in your app's folder until you find one with a .txt file extension.

However, there is nothing in the standard C++ libraries to handle that.

You need to use platform-specific APIs 1 to determine the folder where your app is running from, and then you can use platform-specific APIs 2, or a 3rd party cross-platform API 3, to enumerate the files in that folder.

Once you discover the file, only then can you open it.

1: (like parsing the result of GetModuleFileName() on Windows)
2: (like FindFirstFile() and FindNextFile() on Windows)
3: (like boost::filesystem)

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • The C++17 [filesystem library](http://en.cppreference.com/w/cpp/filesystem) will be almost exactly like `boost::filesystem`, so that may be worth mentioning. – Miles Budnek Aug 01 '16 at 23:39
  • 1
    @MilesBudnek: That is awhile off, though. And considering that many people still aren't even using C++11 yet, it is not likely that they are going to be jumping to C++17 right away. – Remy Lebeau Aug 01 '16 at 23:40