How do I open a C file with a relative path? [closed]
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
开发者_如何学Go Improve this questionI am trying to parse a txt file and I want to reference it relative to my current directory location. If I put the file path in completely it will work but it I try to use ..\src\test.txt it wont find it. Is this not the proper way to reference a file relative up one directory?
Any help would be appreciated
If you put "..\src\test.txt" in a string constant, you need to double all the backslashes so that "\t" and "\s" are not interpreted as escape sequences. (Or you can use forward slashes instead, which is more portable.)
It will depend on what the current working directory is set to. By default it is the directory the executable resides in if you double-click the app from Explorer, or the current path the shell is in if started from a command prompt.
If test.txt is in c:\code\app\src and your application is in c:\code\app, the relative path "..\src\test.txt" is going to end up c:\code\src\test.txt (if launched from explorer).
Try printing the output of _getcwd before you try opening the file to verify what directory is the current working directory.
Assuming that your directory structure looks like:
project +---src | test.txt | proj.c \---bin a.out <- Working directory
your relative path is correct; your working directory is actually on the same level as the text file.
If you really mean that the file is up one directory as you stated, like this: (Note: This is an awkward project structure)
project \---src | test.txt | proj.c \---bin a.out
or like this: (makes more sense)
project | test.txt +---src | proj.c \---bin a.out
Then the path you need is "../test.txt"
or, equivalently, "../../project/test.txt"
A better location would be in a data directory, so your path would be "../data/test.txt"
I guess this is a windows VS vbuild (given the back slashed path)
VS will have put the binary in something like project\bin\debug. And when you run it in VS it will set the current WD to the location of the binary.
so
a) copy the file to the right place
b) change the project properties debug setup to say set the current path to the place where you expect the file to be (relatively)
精彩评论