打开 C 中其他目录中的 txt 文件

Open txt file present in some other directory in C

我想打开“../ab cd/Output”文件夹中的文件 abc.txt。 到目前为止我所做的是:

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

执行时出现分段错误。

问题应该只是文件路径本身

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

你的实际 path 是无效的 "../ab\ cd/Output/abc.txt",你不需要在这里转义任何东西。

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");

我正在为 / 添加一个额外的 strcat,因为我不知道目录名称的来源。有人可能会在没有尾随 / 的情况下指定它。如果他们在名称中指定 /,那不会有什么坏处。

/dir/one等于dir //两个