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/