How to open a text file that's not in the same folder?

前端 未结 3 486
故里飘歌
故里飘歌 2021-01-26 05:28

Since C it\'s not a language I am used to program with, I don\'t know how to do this.

I have a project folder where I have all the .c and .h files and a conf folder unde

相关标签:
3条回答
  • 2021-01-26 06:26

    You're probably going to want to look into the dirent family of routines for directory traversal.

    0 讨论(0)
  • 2021-01-26 06:28

    The location of your .c and .h files is not really the issue; the issue is the current working directory when you run your executable.

    Can you not pass in the full path to the fopen() function?

    0 讨论(0)
  • 2021-01-26 06:29

    The easy way is to use an absolute path...

    my_file = fopen("/path/to/my/file.txt", "r");
    

    Or you can use a relative path. If your executable is in /home/me/bin and your txt file is in /home/me/doc, then your relative path might be something like

    my_file = fopen("../doc/my_file.txt", "r");
    

    The important thing to remember in relative paths is that it is relative to the current working directory when the executable is run. So if you used the above relative path, but you were in your /tmp directory and you ran /home/me/bin/myprog, it would try to open /tmp/../doc/my_file.txt (or /doc/my_file.txt) which would probably not exist.

    The more robust option would be to take the path to the file as an argument to the program, and pass that as the first argument to fopen. The simplest example would be to just use argv[1] from main's parameters, i.e.

    int main(int argc, char **argv)
    {
        FILE *my_file = fopen(argv[1], "r");
        /* ... */
        return 0;
    }
    

    Of course, you'll want to put in error checking to verify that argc > 2, etc.

    0 讨论(0)
提交回复
热议问题