在不同位置的c中打开文件

Opening a file in c which is in diffrent location

#include <unistd.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>


uid_t ruid=-1, euid=-1, suid=-1;



int main() {
FILE *fh = fopen("file.txt", "r");
char c;
while ((c = fgetc(fh)) != EOF) {
    printf("%c", c);
}
return 0;

}

伙计们,我必须使用 c fopen 命令打开这个文件,但我必须指定文件实际所在的位置。也就是说,例如上面的 file.txt 不在程序正在执行的位置,而是在不同的位置,例如上面的 file.txt 在 /home/my_user_name 和正在执行的程序是/home/my_user/anyfolder。 所以我想知道如何在程序中指定文件的位置。 提前致谢

您只需指定路径.......

fopen("/path/to/file.txt", "r")

FILE *fh = fopen("../file.txt", "r");

如果您不知道如何指定路径。
您也可以这样做:

char path[] = "../";  // or "/home/my_user_name/"
char file[] = "file.txt";
char full[256];

snprintf(full, sizeof(full), "%s%s", path, file);
FILE *fh = fopen(full, "r");

但不要忘记错误处理。

编辑:错误检查:

#include <unistd.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>

int main() {
    int c;
    char path[] = "../";   // or "/home/my_user_name/"
    char file[] = "file.txt";
    char full[256];

    snprintf(full, sizeof(full), "%s%s", path, file);

    FILE *fh = fopen(full, "r");

    if (fh != NULL) {
        while ((c = fgetc(fh)) != EOF) {
            printf("%c", c);
        }
        fclose(fh);
    } else {
        printf("could not open file");
    }
    return 0;
}

您可以使用 /home/my_user_name/file.txt 作为参数而不是 file.txt:

FILE *fh = fopen("/home/my_user_name/file.txt", "r");

或者您可以使用相对路径(我不推荐这样做,因为这需要您的程序位于特定位置才能正常运行):

FILE *fh = fopen("../file.txt", "r");

这就是您检查文件是否成功打开的方法。

FILE * pFile;

pFile = fopen ("test.txt","r");
if (pFile!=NULL)    //check if file was opened successfully
{
    //do stuff
}
return 0;

直接输入路径名:fopen("/path/to/file.txt", "r").

如果要检查错误,只需检查 return 值即可。像这样:

FILE *fh = fopen("/path/to/file.txt", "r");

if (fh == NULL) {
    // print error
    // exit program if you want to.
}

您可以使用 exit 函数退出程序。在这种情况下,你想因为错误而退出,所以exit (1);