C从配置文件中读取值

Ant*_*ton 0 c parsing config

我需要帮助从配置文件中读取端口.该行看起来像: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;
Run Code Online (Sandbox Code Playgroud)
  // open file
  // some feof code   
Run Code Online (Sandbox Code Playgroud)

[..]

        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]);
Run Code Online (Sandbox Code Playgroud)

这按预期工作^^但是,当尝试复制到缓冲区时,我没有得到任何端口或我得到默认端口.

                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);
}
Run Code Online (Sandbox Code Playgroud)

unw*_*ind 8

您应该只使用fscanf():

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