-4

I am having trouble with the function fopen(). I would always send the exact location of a file as an arguement to fopen(), which would look something like this:

fopen("c:\\Users/Username/Desktop/Projects/program_name/version 1.0/data/important_data.txt", "r");

That works just fine on my computer, but what if I decide to transfer the program to another computer? The location would completely change.

It would no longer be:

c:\\Users/Username/Desktop/Projects/program_name/version 1.0/data/important_data.txt

But it would rather be something like:

c:\\Users/OtherUsername/Desktop/program_name/version 1.0/data/important_data.txt

My question is, how do I make a portable function which can obtain the location of a file, if I only give the name (including the type e.g. .txt) of the file to the function?

Keep in mind, I've been learning C for less than a year. There are still a lot of things which I must learn, and things like this are of high importance.

octagonlord69
  • 65
  • 1
  • 2
  • 6
  • 1
    Sounds like the easiest solution to me is to simply distribute the necessary files along with your executable. Zip/tar up the top level directory with all supporting files in that hierarchy, or have the user/install script define some kind of environment variable that points to the files. No programs go searching all over the file system for the files they need.. they know where they are. – yano Oct 10 '17 at 19:50
  • 2
    The C99 standard does not know about directories. But POSIX does. Your question is operating system specific. You might want [readdir(3)](http://man7.org/linux/man-pages/man3/readdir.3.html), [nftw(3)](http://man7.org/linux/man-pages/man3/nftw.3.html), [stat(2)](http://man7.org/linux/man-pages/man2/stat.2.html) – Basile Starynkevitch Oct 10 '17 at 19:54
  • 2
    What you describe needing to know is the standards for software installation on the target operating system. That varies greatly from one OS to another. – Lee Daniel Crocker Oct 10 '17 at 19:55

1 Answers1

0

this is operating system specific. on linux you can use the locate shell command and parse its output ( http://www.linfo.org/locate.html )

C: Run a System Command and Get Output?

How do I execute a Shell built-in command with a C function?

however this solution will only work on linux. i think yano's solution in the comments above is better ...

ralf htp
  • 8,134
  • 3
  • 19
  • 30