I have a comma delimited list of boats and their specs that I need to read into a struct. Each line contains a different boat along with their specs so I have to read the file line by line.
Sample Input File (the file I'll be using has over 20 lines):
pontoon,Crest,Carribean RS 230 SLC,1,Suzuki,115,Blue,26,134595.00,135945.00,1,200,0,250,450,450,0
fishing,Key West,239 FS,1,Mercury,250,Orange,24,86430.00,87630.00,0,0,250,200,500,250,0
sport boat,Tahoe,T16,1,Yamaha,300,Yellow,22,26895.00,27745.00,0,250,0,0,350,250,0
I have a linked list watercraft_t:
typedef struct watercraft {
char type[15]; // e.g. pontoon, sport boat, sailboat, fishing,
// canoe, kayak, jetski, etc.
char make[20];
char model[30];
int propulsion; // 0 = none; 1 = outBoard; 2 = inBoard;
char engine[15]; // Suzuki, Yamaha, etc.
int hp; // horse power
char color[25];
int length; // feet
double base_price;
double total_price;
accessories_t extras;
struct watercraft *next;
} watercraft_t;
My main function opens the file and stores it in a pointer:
FILE * fp = fopen(argv[1], "r"); // Opens file got from command line arg
This file is then passed to a function that should parse exactly 1 line and then return that node to be placed inside of a linked list.
// Create watercrafts from the info in file
watercraft_t *new_waterCraft( FILE *inFile )
{
watercraft_t *newNode;
newNode = (watercraft_t*)malloc(sizeof(watercraft_t));
fscanf(inFile, "%s %s %s %d %s %d %s %d %lf %lf", newNode->type, newNode->make, newNode->model, &(newNode->propulsion), newNode->engine, &(newNode->hp), newNode->color, &(newNode->length), &(newNode->base_price), &(newNode->total_price));
return newNode;
}
When calling a function to print just the type of each boat this is the result:
1. pontoon,Crest,CRS
2. SLC,1,Suzuki,11fishing,Key
3. SLC,1,Suzuki,11fishing,Key
4. SLC,1,Suzuki,11fishing,Key
5. SLC,1,Suzuki,11fishing,Key
6. SLC,1,Suzuki,11fishing,Key
7. SLC,1,Suzuki,11fishing,Key
8. SLC,1,Suzuki,11fishing,Key
9. SLC,1,Suzuki,11fishing,Key
10. SLC,1,Suzuki,11fishing,Key
11. SLC,1,Suzuki,11fishing,Key
12. SLC,1,Suzuki,11fishing,Key
13. SLC,1,Suzuki,11fishing,Key
14. SLC,1,Suzuki,11fishing,Key
15. SLC,1,Suzuki,11fishing,Key
16. SLC,1,Suzuki,11fishing,Key
17. SLC,1,Suzuki,11fishing,Key
I've narrowed the issue down to how I'm reading the values from the file with fscanf.
The first thing I attempted was to use %*c in between all of my placeholders but after running that, my output looked exactly the same. The next thing I realized is that I won't be able to use fscanf because the text file will have whitespace that needs to be read.
My next thought was to use fgets but I don't think I will be able to use that either because I'm not sure how many characters will have to be read each time. I just need it to stop reading at the end of the line while separating the values by the comma.
I've been searching for answers for a few hours now but nothing has seemed to work so far.