【问题标题】:Opening a file in c which is in diffrent location在c中打开位于不同位置的文件
【发布时间】:2016-01-26 08:23:21
【问题描述】:
#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。 所以我想知道如何在程序中指定文件的位置。 提前致谢

【问题讨论】:

  • 注意:c 应该是 int

标签: c fopen


【解决方案1】:

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

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

【讨论】:

  • 嘿,但它说分段错误
  • 然后在尝试读取之前添加一个测试以查看fopen 是否成功!
  • 我是新手,能告诉我怎么做吗?
  • 查看我的回答 FILE *fh = fopen("../file.txt", "r"); 并确保文件位于正确的位置并具有正确的名称。测试是否成功,只需检查fopen的返回值是否不为null
【解决方案2】:
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;
}

【讨论】:

    【解决方案3】:

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

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

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

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

    【讨论】:

      【解决方案4】:

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

      如果要检查错误,只需检查返回值。像这样:

      FILE *fh = fopen("/path/to/file.txt", "r");
      
      if (fh == NULL) {
          // print error
          // exit program if you want to.
      }
      

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

      【讨论】:

        【解决方案5】:

        这就是你如何检查文件是否打开成功。

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2014-05-03
          • 1970-01-01
          • 1970-01-01
          • 2020-10-24
          • 1970-01-01
          • 2022-07-21
          • 1970-01-01
          相关资源
          最近更新 更多