In: Computer Science
Write a C program that will read different data types from the following file and store it in the array of structures.
Given file: (This file have more than 1000 lines of similar data):
time | latitude | longitude | depth | mag | magType | nst | gap | dmin |
2020-10-19T23:28:33.400Z | 61.342 | -147.3997 | 12.3 | 1.6 | ml | 12 | 84 | 0.00021 |
2020-10-19T23:26:49.460Z | 38.838501 | -122.82684 | 1.54 | 0.57 | md | 11 | 81 | 0.006757 |
2020-10-19T23:17:28.720Z | 35.0501667 | -117.6545 | 0.29 | 1.51 | ml | 17 | 77 | 0.1205 |
2020-10-19T22:47:44.770Z | 38.187 | -117.7385 | 10.8 | 1.5 | ml | 15 | 100.22 | 0.049 |
2020-10-19T22:42:26.224Z | 54.4198 | -159.9943 | 18.7 | 2.9 | ml |
Create a structure like below and make an array of structures in the main C file and store the data based on their data types.
struct data
{
char time[100];
float latitude;
float longitude;
float depth;
float mag;
char magType[5];
char nst[5];
int gap;
float dmin;
};
#include<stdio.h> #include<string.h> #include <stdlib.h> struct data{ char time[100]; float latitude; float longitude; float depth; float mag; char magType[5]; char nst[5]; int gap; float dmin; }; int main(){ struct data records[1000]; struct data temp; char str[256]; int result,i=0; FILE* f = fopen("/home/user/Downloads/file.csv", "r");// for a csv file result = fscanf(f, "%255[^;\n]", str); result = fscanf(f, "%255[^;\n]", str);// read data from the user while(result != EOF){ if(result == 0){ result = fscanf(f, "%*c"); } else{ char *token = strtok(str,","); int j = 0; while(token != NULL) { if(j == 0) strcpy(records[i].time, token); else if(j == 1) records[i].latitude = atof(token); else if(j == 2) records[i].longitude = atof(token); else if(j == 3) records[i].depth = atof(token); else if(j == 4) records[i].mag = atof(token); else if(j == 5) strcpy(records[i].magType, token); else if(j == 6) strcpy(records[i].nst, token); else if(j == 7) records[i].gap = atoll(token); else records[i].dmin = atof(token); token = strtok(NULL, ","); j++; } i++; printf("\n"); } result = fscanf(f, "%255[^;\n]", str); } for(int x=0; x<i; x++){ for(int y=0; y<i-1; y++){ if(records[y].latitude > records[y+1].latitude){ temp = records[y]; records[y] = records[y+1]; records[y+1] = temp; } } } return 0; }
Explanation:
Just create a file named file.csv and the program will read the text in it.
This will make the following line of code find your csv file..FILE* f = fopen("/home/user/Downloads/file.csv", "r");