I did some code to refresh my C. So many things have happened since 1987, but at least I started with ANSI instead of K&R. As I used the language so little, I think it is time to do some practise and even to learn some C++ to support my Python coding.
See my code and tell, where I am doing stupid things. This is half copy of one other thread's code, but as I did not understand/trust the linked list part, I simplified it to simple array based fixed memory allocation version to practice structs and file IO. %s format I could not get to work with my input so I resorted to other formats. Fields are separated by ';' and unquoted.
#include <stdio.h>
#define MAXDATA 100
struct entry {
char first_name[15];
char last_name[20];
char date_of_birth[11];
char email[45];
char phone[15];
char address[50];
char city[15];
char zipcode[6];
};
int main(int argc, char* argv[])
{
char buffer[255];
int i, index;
struct entry contacts[MAXDATA];
FILE* myfile;
struct entry next_data;
// with one parameter use it for input file, otherwise use "data.csv" default
if(argc == 2){
myfile = fopen(argv[1], "r");
if (myfile) printf("Opened datafile %s\n", argv[1]);
} else myfile = fopen("data.csv", "r");
if(!myfile) {
printf("Input file did not exist!");
return 1;
}
printf("Reading from the file...");
i = 0;
while(fgets(buffer, 255, myfile) != NULL && i < MAXDATA) {
sscanf(buffer,
" %15[^;\t\n] ; %20[^;\t\n] ; %11[^;\t\n] ; %45[^;\t\n] ; %15[^;\t\n] ; %50[^;\t\n] ; %15[^;\t\n] ; %6[^;\t\n]",
next_data.first_name, next_data.last_name, next_data.date_of_birth, next_data.email, next_data.phone,
next_data.address, next_data.city, next_data.zipcode);
contacts[i++] = next_data;
//printf("\nzip %s", next_data.zipcode); //debug print of last info at line
};
printf("\n%d names entered.\n---------------------\n", i);
// printing various info for test
contacts[i].first_name[0] = '\0';
for(index = 0; contacts[index].first_name[0] != 0 && index < MAXDATA; index++) {
printf("\n%s, %s (born %s)\n%s (%s)\nphone: %s\n",
contacts[index].last_name, contacts[index].first_name, contacts[index].date_of_birth,
contacts[index].address, contacts[index].city, contacts[index].phone);
}
return 0;
}
example data.csv file (data scrambled):
Tony;Fine;01.07.1965; tony.fine@gmail.com;0503711775;Kalastajantie 1 C 4;ESPOO;02230
Edlira;Alimerko; 01.12.1965;edlira.alimerko@gmail.com;0502220912; Kalastajantie 1 C 4;ESPOO;02230
Seppo;Suomalainen; 01.02.1950;seppo.suomalainen@suomi.fi; 050342134927;Suvikumpu 4;ESPOO;02130