I want to create a file in the other directory, not where the original program is saved.
FILE * fp;
fp=fopen("a.txt","w");
But I want to change the directory where to create/write a file.
I want to create a file in the other directory, not where the original program is saved.
FILE * fp;
fp=fopen("a.txt","w");
But I want to change the directory where to create/write a file.
It depends on the type of operating system you are using.
If you are using Linux or a similar system, and you want to create the file in a directory /home/username/folder
(assuming you have write permissions in that directory), you can simply do:
FILE * fp;
fp=fopen("/home/username/folder/a.txt","w");
If you are using Windows, and you want to create a file in C:\Users\username\folder
(assuming write permissions), you can do:
FILE * fp;
fopen("C:\\Users\\username\\folder\\a.txt", "w");
Note that you have to escape the \
character for paths on Windows platform, because when we have a \
(backslash) inside a string, it is interpreted as an escape sequence and is implicitly associated with the next character, like \n
or \t
. But since we are not using any escape sequence, and want an actual \
, we must insert an escape sequence \\
for it.
As pointed out by @stark, we can also use a /
(forward slash) for paths inside a string instead of \\
.
In general fopen
is syntaxed like this:
fopen("path/to/file", ...)
If only a name is given, then it is assumed to be in the same folder as the executable. So if you want to do stuff in another folder you shall put the path of that folder like this:
fp = fopen("<path>/a.txt", "w");