Hey,

I am trying to open a file with a relative pathname:
e.g. file=fopen("/files/index.html");
where the files directory is in the same location as the executable.
For some reason the executable cannot locate the file. Why?

Thanks, Elise

[Edit]

OK it works without the initial slash in the path name but I can't figure out how to remove it from the char[]?

Dani AI

Generated

As discovered, the leading slash is the root cause. On Unix-like systems a pathname that begins with / is absolute (rooted at /), so the runtime will look for the file from the filesystem root. A path without the leading slash is relative to the process' current working directory (CWD) — not automatically relative to the executable's folder. That difference is why a path that works when you run from the exe directory can fail when the program is launched from an IDE, a service, or a different CWD.

If you want to strip a single leading slash in-place, a safe approach is to shift the remainder of the string left with memmove so the terminating NUL is preserved:

#include <string.h>

if (path[0] == '/') {
    size_t src_len = strlen(path + 1);
    memmove(path, path + 1, src_len + 1); /* copy including NUL */
}

As a quicker (non-copying) trick, pass path + 1 to fopen when the first character is /. That avoids modification but only works if you never need the original base pointer later.

If files must live beside the executable, compute the executable directory instead of relying on CWD. Platform helpers exist (readlink on /proc/self/exe for Linux, _NSGetExecutablePath on macOS, GetModuleFileName on Windows); then join that directory and filename with a path separator. Also note Windows semantics: a leading backslash/slash refers to the root of the current drive, so behavior differs from POSIX. This explains the original surprise and gives reliable ways to open the intended file — answering ’s follow-up.

Thanks, but I figured it out. Elise

Thanks, but I figured it out. Elise

What was it? :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.