【问题标题】:Pass a relative path to fopen()将相对路径传递给 fopen()
【发布时间】:2012-02-02 22:17:40
【问题描述】:

我正在尝试将相对路径传递给 fopen(),但它似乎无法找到该文件。我需要这个才能在 Linux 上工作。 文件名(例如:t1.txt)保存在一个数组中。所以我需要的只是相对路径的“前面部分”。

这是我的代码:

// Use strcat to create a relative file path
char path[] = "./textfiles/"; // The "front part" of a relative path
strcat( path, array[0] ); // array[0] = t1.txt

// Open the file
FILE *in;
in = fopen( "path", " r " );
if (!in1) 
{
    printf("Failed to open text file\n");
    exit(1);
}

【问题讨论】:

    标签: c linux file-io


    【解决方案1】:
    in = fopen("path", " r ");
    

    这里有两个错误:

    1. 您不想打开字面上命名为“路径”的文件,您想要名称在变量path 中的文件
    2. 模式参数无效;你想要"r"

    为了让他们做对

    in = fopen(path, "r");
    

    【讨论】:

    • 哇哦,哈哈!我自己永远不会发现第一个错误。是的,我喜欢添加空格,这样代码就不会显得拥挤。估计是个坏主意!无论如何,谢谢!
    • 不要忘记其他答案中的建议,特别是数组path 的大小,并且当您的FILE *in 时不要测试in1
    【解决方案2】:

    首先,您需要在path 中添加一些空间,以便在strcat 中容纳array[0] 的内容,否则您将超出分配的区域。

    其次,您没有将path 传递给fopen,因为您将"path" 括在双引号中。

    char path[100] = "./textfiles/"; // Added some space for array[0]
    strcat( path, array[0] );
    
    // Open the file
    FILE *in;
    in = fopen( path, " r " ); // removed quotes around "path"
    if (!in) 
    {
        printf("Failed to open text file\n");
        exit(1);
    }
    

    【讨论】:

    • 我想你的意思是说strcat( path, argv[1] ),因为argv[0]是当前程序的名称。
    • @markgz 谢谢!实际上,我的意思是说 array[0] 遵循 OP 的代码,但是智能感知放了 argv,我没有注意到。现在已修复。
    【解决方案3】:

    path 仅大到足以包含初始化时使用的字符。 path 的大小必须增加。根据附加的文件名为path 分配内存:

    const char* dir = "./textfiles/";
    const size_t path_size = strlen(dir) + strlen(array[0]) + 1;
    char* path = malloc(path_size);
    if (path)
    {
        snprintf(path, path_size, "%s%s", dir, array[0]);
    
        in = fopen(path, "r"): /* Slight differences to your invocation. */
    
        free(path);
    }
    

    【讨论】:

    • 我完全没有想到这一点。感谢您的回复!
    【解决方案4】:

    您的问题与fopen 和C 字符串处理无关:strcat 要求目标缓冲区中有足够的内存用于整个字符串,但您只为 initial 字符串。坏的!顺便说一句,使用valgrind 之类的工具会立即告诉您您的非法访问。

    这是一个幼稚的解决方案:

    char buf[1000] = { };
    strcat(buf, "./textfiles/");
    strcat(buf, array[0]);
    
    // ...
    

    【讨论】:

      猜你喜欢
      • 2020-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多