C 从配置文件中读取值

标签 c parsing config

I need help with reading a port from a config file. The line looks like: PORT=8888

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


int main(int ac, char **av)
{

        char buf[256];
        FILE *file = NULL;
        char hostlist[256] = "";
        int port = 8080; /* default not from config */
        int i = 0;
  // open file
  // some feof code   

[..]

        strcpy(hostlist,buf);
        if (strstr(buf,"PORT")) {      /* buf[0-3] = */
                printf("%c\n",buf[5]); /* PORT=8888 */
                printf("%c\n",buf[6]);
                printf("%c\n",buf[7]);
                printf("%c\n",buf[8]);

This works as expected ^^ But, when trying to copy into a buffer I get nothing for port or I get the default port.

                for(i=4;i<9;i++) {
                while (buf[i] != '\n') {
                port += buf[i++];
                printf("buf:%c\n",buf[i]);
                }
                }
                printf("port=%d\n",port);
        }
        fclose(file);
}

最佳答案

你应该只使用 fscanf():

if(fscanf(file, "PORT=%d", &port) == 1)
{
  print("Found port number in config, it's %d\n", port);
}

关于C 从配置文件中读取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9719140/

相关文章:

为 Labview 创建 DLL

html - 常规 : parsing xml with HTML tags inside

java - 从Java中的谷歌地图API解析Json数组

config - 如何为包编写新的 .nix 配置文件?

c - OpenSSL 上的 AES CTR 256 加密操作模式

c - 通过 char* 指针将结构传递给 main

c - 如何检查存储在地址中的各个字节的情况?

python - 必须有一个更优化的方法来解析两个文件

grails - 如何在 Config.groovy 中指定目标目录?

java - 使用 docker 启动 quarkus 时,错误 OIDC 服务器在 'quarkus.oidc.auth-server-url' URL 不可用