【问题标题】:Reading from a configuration file从配置文件中读取
【发布时间】:2012-11-02 08:25:04
【问题描述】:

我正在从一个简单的配置文件中读取路径,并使用 C 语言将其存储到一个 char 数组中。我想出了一种方法来做到这一点,但是在检索路径末尾没有附加空格的情况下遇到了问题。请帮助我找到更好的方法。

char* webroot(){
 FILE *in = fopen("conf", "rt");
 char buff[1000];
 fgets(buff, 1000, in);
 printf("first line of \"conf\": %s\n", buff);
 fclose(in);

 return buff;
}

【问题讨论】:

    标签: c file-io fgets


    【解决方案1】:

    它不是结尾的空白字符序列,而是换行符,因为fgets() 将其包含在返回的缓冲区中:将\n 替换为空终止符:

    /* fgets() will not read the new-line if
       there is not sufficient space in the buffer
       so ensure it is present. */
    char* nl_ptr = strrchr(buff, '\n');
    if (nl_ptr) *nl_ptr = '\0';
    

    由于stdout 上明显换行,它可能看起来好像有一系列空白字符,但这是由于fgets() 读取的换行符的存在。

    当打印字符串时,我发现将字符串放在[] 中以使字符串的内容更清晰:

    printf("first line of \"conf\": [%s]\n", buff);
    

    这将使fgets() 获得的换行符的存在更加明显。

    请注意,函数webroot() 正在返回局部变量buff 的地址:这是一个错误并且是未定义的行为。需要动态分配一个新的缓冲区,如果可用则使用strdup(),否则使用malloc()strcpy()

    return strdup(buff);
    

    webroot() 的调用者必须free() 返回值。安排在发生故障时返回NULL

    【讨论】:

    • 根据操作系统的不同,您可能还有一个 '\r' 字符。
    • 非常感谢您的精彩解释。现在它就像一个魅力:) 再次感谢!!!
    【解决方案2】:

    您可以使用fscanf(fp, "%s", buff) 读取没有空格的字符串。为防止缓冲区溢出,请添加限制 fscanf(fp, "%999s", buff)

    【讨论】:

      【解决方案3】:

      您是否尝试过使用 fscanf?

      fscanf(in, "%s", buff);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-12-24
        • 2012-12-23
        • 2017-07-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-11-24
        相关资源
        最近更新 更多