我需要帮助从配置文件中读取端口。这条线看起来像: 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]);
这按预期工作^^ 但是,当我试图复制到缓冲区时,我什么也得不到 端口或我得到默认端口。
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);
}
答案 0 :(得分:8)
您应该只使用fscanf()
:
if(fscanf(file, "PORT=%d", &port) == 1)
{
print("Found port number in config, it's %d\n", port);
}
答案 1 :(得分:1)
我不太明白这个问题,但我认为你打算做这样的事情:
char* ptr_port = strstr(buf,"PORT=");
if(ptr_port != NULL)
{
int port = get_port(ptr_port);
for(int i=0; i<4; i++)
{
printf("%c", ptr_port[i]);
}
printf("\n");
printf("port=%d\n", port);
}
#include <ctype.h>
int get_port (const char* str)
{
int port = 0;
for(int i=0; str[i]!='\0'; i++)
{
if(isdigit(str[i]))
{
port = port*10 + str[i] - '0';
}
}
return port;
}