I have an input file that contains any number of lines. Each line will follow the same structure. There will be 5 fields, separated by 4 commas. Fields 1 and 3 will be single characters, fields 2,4,5 will be integers. Example:
<A, 123, B, 456, 789>
I need to iterate over each line, parse out the fields, and capture each field value into a separate variables.
header file:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
typedef struct neighbor {
char host[1];
int send_on_port;
int listens_on_port;
int link_cost;
} Neighbor;
.c file:
Code:
int main(int argc, char* argv[])
{
...
while ( fgets ( line, sizeof line, file ) != NULL ) /* read a line */
{
char* p = strchr(line, '<');
char* p2;
p++;
if (*p == *argv[1]) {
// parse this line
fprintf (stdout, "%s", line ); /* write the line */
// first integer
p2 = strtok(line, ',');
fprintf(stdout, "%d\n", atoi(p2));
// second character
p2 = strtok(NULL, ',');
fprintf(stdout, "%s\n", *p);
// second integer
p2 = strtok(NULL, ',');
fprintf(stdout, "%d\n", atoi(p2));
// third integer
p2 = strtok(NULL, ',');
fprintf(stdout, "%d\n", atoi(p2));
}
}
return 0;
}
I've used similar code to this before, but this time I'm getting the dreaded pointer from integer error on my strtok lines:
warning: passing argument 2 of 'strtok' makes pointer from integer without a cast'
What am I doing wrong? Thanks!