Reputation: 20463
Here's my function to get the size of a file using stat():
off_t fsize(const char *filename) {
struct stat st;
if (stat(filename, &st) == 0)
return st.st_size;
fprintf(stderr, "Cannot determine size of %s: %s\n",
filename, strerror(errno));
return -1;
}
I can get the file size just fine by doing:
size = fsize ("byte.bin");
but when I need to get the file from a lower directory from the local directory, let's say "deps/src" directory, it stops prematurely on me with no error message that i expected:
size = fsize ("deps/src/byte.bin");
I wrote a small program that uses the function, copied the byte.bin file to a "deps/byte.bin" and called my fsize function with "deps/byte.bin" and get the error "Cannot determine size of byte.bin: No such file or directory"
If I use an absolute path like "/something/deps/byte.bin" it works.
What am I doing wrong and how show I do this for the relative path?
Upvotes: 1
Views: 236
Reputation: 6745
I'm guessing that what's happening is that you are incorrectly assuming about the working directory. A simple way to test where the working directory is would be to just write a program that simply outputs a file like test.txt
. In many (but not all) cases, the working directory is wherever the executable file is stored. This means that if you are trying to access a file on a relative path, you will likely need to include at least one ..
in your relative path to get out of the bin
directory.
Upvotes: 1