Alex M.
Alex M.

Reputation: 7

How can I save the second word of each line of a file into a char?

I've got a file called "server.cfg" with this content:

NAME SRV-01
MAC 000543D3F4D8

I want to save "SRV-01" and "000543D3F4D8" to 2 char*. I did something like this:

FILE *fileS;
char *name;
char *mac;
char *p;

fileS=fopen("server.cfg","r");
while(fgets(line,1000,fileS)!=NULL){
    if(line[0]=="N"){
        p=strtok(line," ");
        p=strtok(NULL," ");
        name=p;
        printf("Name: %s\n",name);
    }
    if(line[0]=="M"){
        p=strtok(line," ");
        p=strtok(NULL," ");
        mac=p;
        printf("Name: %s Mac: %s\n",name,mac);
    }

The output is:

Name: SRV-01
Name: 000543D3F4D8 Mac: 000543D3F4D8

But I would want this output:

Name: SRV-01
Name: SRV-01 Mac: 000543D3F4D8

I know that the problem is related to the pointers, but I don't know how could I solve it. Any suggestion?

Thanks

Upvotes: 1

Views: 54

Answers (1)

unwind
unwind

Reputation: 399793

You must work with the memory management; strtok() returns a pointer into the input string (line), which of course will be replaced by each successive fgets().

If you have it, you can use strdup() to duplicate the string and store that, or just use arrays rather than pointers and strcpy() the text in.

Also, since you can be pretty sure that your line won't start with both 'n' and 'm', the second if should be an else if. Your handling of upper/lower case there seems dubious, too ('n' doesn't equal 'N').

Upvotes: 1

Related Questions