Reputation: 147
I was trying to read data from a file and inserting the data into a struct array, the file is formatted like so:
...
0087|www.google.com|2017.08.07 12:13:36
0150|www.yahoo.com|2018.10.06 04:03:12
...
where data types are seprated by '|
's, I then use strtok()
to seprate the data, this worked well for both string types timestamp
and domain
, I was able to get the data stored correctly in the struct, however, for the data type customerid
I am only getting the memory address in the struct, how could I solve this? Thanks!
#include <stdio.h>
#include <string.h>
struct AccessRecord {
int customerID;
char domain[256];
char timestamp[21];
};
struct AccessRecord rc[1000];
int main()
{
int i = 0; char line[300];
const char s[2] = "|";
FILE *fd;
fd = fopen("./example_data.ipb","r");
while (fgets(line, sizeof(line), fd)) {
char *token;
token = strtok(line, s);
rc[i].customerID = token;
token = strtok(NULL, s);
strcpy (rc[i].domain , token);
token = strtok(NULL, s);
strcpy (rc[i].timestamp , token);
token = strtok(NULL, s);
i++;
}
fclose(fd);
return 0;
}
Upvotes: 0
Views: 155
Reputation: 882586
Note the two different ways you are extracting data:
token = strtok(line, s);
rc[i].customerID = token; // assignment of char* (to int, so suspect)
token = strtok(NULL, s);
strcpy (rc[i].domain , token); // string copying
This is despite the fact that both of those are strings. Although the customer ID is numeric data, it is stored as a string and should be treated as such.
In other words, since it is an integer in the structure, you can convert it while reading, such as with:
token = strtok(line, s);
rc[i].customerID = strtol(token, NULL, 10);
Upvotes: 1