I am trying to sift through a .csv file and populate a struct at the top of the code in order to spit out the fields into a terribly made table that I slapped together. But whenever I try to compile it, it prints up to 2 fields fine before printing (null). What do? Please help me.
[img]http://i.imgur.com/1eK5uqW.png[/img]
[code]#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
#include <ctype.h>
/* Remember to turn struct into .h */
typedef struct airPdata{
char *siteNumber; //FAA Site Number
char *LocalID; //Airport's "Short Name", ie MCO
char *fieldName; //Airport Name
char *city; //Associated City
char *state; //State
char *latitude; //Latitude
char *longitude; //Longitude
char *controlTower; //Control Tower (Y/N)
}airPdata;
/* Sifts through .csv file and splits strings up into tokens by , delimiter. Returns the token to print function. */
char *getfield(char *line, int num){
char *tok;
for (tok = strtok(line, ","); tok && *tok; tok = strtok(NULL, ",\n"))
{
if(!--num)
return tok;
}
return NULL;
}
/* Print function that spits out tokens sorted by getfield function. */
void print(char *file, FILE *fp, char *line)
{
airPdata *ports;
ports = (airPdata *) malloc(sizeof(airPdata));
ports->siteNumber = malloc(sizeof(char)*1000);
ports->fieldName = malloc(sizeof(char)*1000);
ports->LocalID = malloc(sizeof(char)*1000);
char *tmp=strdup(line);
while(fgets(line, 500, fp))
{
char *tmp=strdup(line);
ports->LocalID = getfield(tmp,2);
ports->siteNumber = getfield(tmp, 1);
ports->fieldName = getfield(tmp, 3);
printf("%s %s %s\n", ports->siteNumber, ports->LocalID, ports->fieldName);
free(tmp);
}
}
int main()
{
//airPdata *ports;
char file[20];
char line[1000];
int col;
int row;
printf ("Input Desired File Name: ");
scanf ("%s", &file);
FILE *fp = fopen(file, "r");
if(fp==NULL)
{
printf("\nNo file...\n");
return -1;
}
printf("\nFAA Site# Short Name Airport Name ");
printf("City ST Latitude ");
printf("Longitude Tower\n");
printf("---------- ---------- ---------- ");
printf("---- -- -------- ");
printf("--------- -----\n");
print(file, fp, line);
fclose(fp);
return 0;
}
[/code]
When you use strtok(), you actually replace the token value you're looking for with a null character. In this example, what happened is you have a string like this: "value1,value2,value3,value4".
You first look for the second value and the string turns into this: "value1\0value2\0value3,value4" and you are able to get "value2" successfully. During the second round, you look for the first value and so strtok just returns the value from position 0, so you get "value1" successfully. At the final round, you look for the third value and since strtok just looks until it hits a null character, it hits that null character right after "value1" and returns null.
What I would do is use a combination of strchr() to grab the locations of the delimiter commas and then strncpy() to copy the respective strings into their location.
Sorry, you need to Log In to post a reply to this thread.