【问题标题】:Concatenate an environment variable and a string in C and feed to fopen()在 C 中连接一个环境变量和一个字符串并提供给 fopen()
【发布时间】:2018-08-31 10:26:16
【问题描述】:

我对 C 知之甚少,无法完成这个简单的任务:

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

void load_hex_fw() {
    char *warea = getenv("WORKAREA");
    char hex[] = "/path/to/fw.hex";
    char hexfile; // several trials done here (*hexfile, hexfile[500], etc.)
    strcat(hexfile, *warea);
    strcat(hexfile, hex);
    printf("## %s\n", hexfile);
    FILE *file = fopen(hexfile, "r");
    fclose(file);
}

上面的代码基本上是打开一个文件来读取。但是由于 hex 文件的绝对路径很长(而且我也在考虑将来重用这个函数),所以我需要给 fopen() 提供一个灵活的 hexfile 变量。谷歌搜索字符串连接总是给我strcat()strncat,但我总是遇到分段错误。我对指针和引用感到困惑。任何帮助是极大的赞赏。提前致谢!

【问题讨论】:

  • 您必须将字符串连接到字符串,而不是将字符串连接到字符。您发布的代码甚至不应该编译。
  • 代码不应该编译。你应该有#include &lt;string.h&gt;。由于hexfile 是单个字符,而不是它们的大数组,因此调用strcat() 时会出现错误。如果前面没有&amp;,你不能将它传递给strcat();但即使使用&amp;,您也无法安全地将其传递给strcat(),因为它必须是一个数组。
  • 请注意,strncat() 绝不是解决方案的一部分;它本身就是一个问题,使用它会使你的问题变得更糟。

标签: c string environment-variables concatenation


【解决方案1】:

asprintf 为你分配内存

#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>

void main() {
    char *warea = getenv("WORKAREA");
    if (!warea) {
        warea = "default"; // or exit
    }
    char hex[] = "/path/to/fw.hex";
    char *hexfile;
    asprintf(&hexfile, "%s%s", warea, hex);
    printf("## %s\n", hexfile);
    // ...
    free(hexfile);
}

它接受0,但结果并不是你想要的fopen

## (null)/path/to/fw.hex

【讨论】:

    【解决方案2】:

    我在您的代码中添加了一些更正和 cmets,这应该对您有所帮助:

    void load_hex_fw() {
        char *warea = getenv("WORKAREA"); //check if getenv returns null
        if(warea == NULL)
        {
        return;
        }
        char hex[] = "/path/to/fw.hex";
        char *hexfile = NULL;//you need char buffer to store string 
        hexfile = malloc(strlen(warea) + stren(hex) + 1);//ENsure hexfile holds full filename
        strcpy(hexfile,warea); //assuming you hold path in warea
        strcat(hexfile, hex);//Assuming ypu hold filename in hex
        printf("## %s\n", hexfile);
        FILE *file = fopen(hexfile, "r");// check if fopen returns NULL
        fclose(file);
        free(hexfile);
    }
    

    【讨论】:

    • 如果$WORKAREA 中的值足够大,就会出现缓冲区溢出。您不妨展示如何防止这种情况(答案是not,重复notstrncat())。
    • strcpy() 改变了一切。我认为只使用strcat()warea 将简单地将其字符串值附加到hexfile(我不断更改为*hexfilehexfile[500]*hexfile[] 等,只是为了看看哪个最终会工作)并将结果存储到hexfile指向的内存地址。
    • 对于健壮的代码,必须检查 (!=NULL) 调用 malloc()fopen() 的返回值。强烈建议,当系统函数调用无法向stderr输出消息时,包含与errno相关的文本字符串,建议使用perror()执行该活动。
    猜你喜欢
    • 2016-08-08
    • 1970-01-01
    • 2017-12-18
    • 2020-06-07
    • 2011-07-05
    • 2021-12-29
    • 2016-10-29
    • 1970-01-01
    • 2015-01-17
    相关资源
    最近更新 更多