Search code examples
clinuxwindowsfopen

fopen fails in C if slash '/' is put before directory's name


If I open a file in C in any of the following ways, then fopen works fine.

fopen("file.txt", "w");
fopen("/file.txt", "w");
fopen("dir/file.txt", "w");

If I put a slash '/' (or '\' in case of Windows) before directory's name as follows, then fopen fails (returns NULL).

fopen("/dir/file.txt", "w");

It happens both on Windows (MSVC) and Linux. What is the reason of it? Should I expunge starting slash '/'?


Solution

  • you need to add "." infront of the "/"

    ex : fopen("./dir/file.txt", "w");

    if you start with "/" it will start from the root directory. That is the reason fopens returns null