user1465557
user1465557

Reputation: 349

Open txt file present in some other directory in C

I want to open a file abc.txt present in "../ab cd/Output" folder. What I have done so far is:

char temp1[100], temp2[10] = "abc.txt";
strcpy(temp1, "../ab\ cd/Output/");
FILE *fp_minenergy = fopen(strcat(temp1, temp2), "r");

On executing it gives segmentation fault.

Upvotes: 0

Views: 3373

Answers (2)

Robert Jacobs
Robert Jacobs

Reputation: 3360

char dirname[51] = "/the/directory";
char filename[51] = "the_file_name.txt";
char full_name[101]  = strcat("/the/directory","/");
char full_name = strcat(full_name,filename);
FILE *fp_minenergy = fopen(full_name, "r");

I am adding an extra strcat for the / because I don't know where the directory name is coming from. Someone may specify it without the trailing /. If they specify the / in the name, it doesn't hurt.

/dir/one is equal to dir//two

Upvotes: 0

Peter
Peter

Reputation: 2320

The problem should be just the file path itself

fopen("../ab cd/Output/abc.txt", "r");

Your actual path is not valid "../ab\ cd/Output/abc.txt", you don't need to escape here anything.

Upvotes: 1

Related Questions