MonkeyImpala
MonkeyImpala

Reputation: 129

How to open file inside folder in current directory using fopen?

I want to open a file that is inside a folder in the current working directory like so:

fopen("/folder/file.txt","r");

I'm unable to do so in this way, I get a No such file or directory error.

How can I do this properly?

Upvotes: 9

Views: 61109

Answers (4)

MonkeyImpala
MonkeyImpala

Reputation: 129

It seems that if I remove the first backslash it works.

Like so:

fopen("folder/file.txt","r");

Weird.

Upvotes: -1

richy wayne
richy wayne

Reputation: 1

int folder;
char* foldername="Ricci";
folder = mkdir(foldername);
DIR* opendir(foldername);
printf("folder successfully created\n");
FILE* fp;
fp = fopen("Ricci/database.txt","a");

Upvotes: -1

Karthikeyan.R.S
Karthikeyan.R.S

Reputation: 4041

You have to mention that is a current directory. Try this,

fopen("./folder/file.txt","r");

Or

fopen("folder/file.txt","r");

If you mentioning like this /folder/file.txt it will search the directory from the root directory. So this is the reason for getting the error.

Upvotes: 13

David Ranieri
David Ranieri

Reputation: 41017

Try:

fopen("./folder/file.txt","r"); /* dot means the directory itself */

or

fopen("folder/file.txt","r"); /* without the first backslash */

Upvotes: 2

Related Questions