gpt4 book ai didi

C 从配置文件中读取值

转载 作者:太空宇宙 更新时间:2023-11-04 05:14:38 25 4
gpt4 key购买 nike

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com