Reputation: 105
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);
}
Upvotes: 0
Views: 4790
Reputation: 213809
I don't quite understand the question, but I assume you intend to do something like this:
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;
}
Upvotes: 1
Reputation: 399813
You should probably just use fscanf()
:
if(fscanf(file, "PORT=%d", &port) == 1)
{
print("Found port number in config, it's %d\n", port);
}
Upvotes: 8