How to get rid of the complete direction to the file.



  • The project created a folder of "levels" and put a file with a map there, and if you sign the whole way, it works.

    ifstream level;
    level.open("/users/Stolz/git/Roguelike/levels/level" + to_string(aLevelNumber) + ".map");
    

    But if you indicate the way "levels/level" + to_string(aLevelNumber) + ".map" If he doesn't see the file, how can he fix it?



  • There are a few ways to ask for a "down," that is, a headline, knowing that we can figure out all the ways we need to get to the configuration files, etc.

    This may be a variable environment, a home-based user catalogue that launched the program and a catalogue containing the code.

    The launch system first puts her name on the program, as the user introduced it in the shell (or what the programmer pointed out to her through http://linux.die.net/man/3/execl )

    If the name of the launch programme does not contain an absolute or relative (referring to its name) of the catalogue), the system is looking for a catalogue of the programme code in the variable environment (environment) PATHwhere by the symbol : The catalogues are listed.

    Using these knowledge, it is easy to write a couple of functions that, with the name of the command line, return the catalogue of the programme launched.

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <limits.h>
    #include <unistd.h>
    

    char *
    srcpath (const char *pgm)
    {
    char *path = getenv("PATH"),
    dir[PATH_MAX], *p;

    if (path)
    for (p = path; *p; *p ? p++ : p) {
    char *t = dir, *e = dir + PATH_MAX - 1;

      while (*p &amp;&amp; *p != ':' &amp;&amp; t &lt; e)
        *t++ = *p++;
      if (snprintf(t, e - t, "/%s", pgm) &lt; e - t &amp;&amp;
          access(dir, R_OK | X_OK) == 0)
        return strndup(dir, t - dir);
    }
    

    return 0;
    }

    char *
    srcdir (const char *av0)
    {
    const char *pgm = strrchr(av0, '/');

    return pgm ? strndup(av0, pgm - av0) : srcpath(av0);
    }

    int
    main (int ac, char *av[])
    {
    char *dir;

    for (; *av; av++) {
    printf("%s : %s\n", av[0], dir = srcdir(av[0]));
    free(dir);
    }

    return puts("End") == EOF;
    }

    At least Linux (from 2.2) in the catalogue http://linux.die.net/man/5/proc There's a file for each process (in fact a symbolic line) /proc/[pid]/execontaining a complete path to the completed file.

    Write a similar function that extracts a catalogue from /proc:

    char *
    linux_srcdir ()
    {
    char buf[PATH_MAX];
    int n = readlink("/proc/self/exe", buf, PATH_MAX);

    return n > 0 ? buf[n] = 0, strndup(buf, strrchr(buf, '/') - buf) : 0;
    }


Log in to reply
 


Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2