user3746220
user3746220

Reputation: 11

Parsing CSV data into structure

I have to put the data from a csv file (name, address, telephone...) to a structure of my C program. It's been unsuccessful, unfortunately. I tried using strtok function to break into tokens every time it finds a ";" (because we're dealing with a Comma Separated File).

Here's what I've done:

#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#define MAX_STR_LEN 256
#define MAX_BOOKS 256


struct estrutura
{
    int id;
    char nome[40];
    char endereco[40];
    char cidade[40];
    char pais[20];
    char cep[10];
    char nasc[12];
    char telefone[14];
    char total[20];
};

struct estrutura cliente[200];

FILE *pFile;

//allocate buffer in each line

char *buf = malloc(MAX_STR_LEN);
char *tmp; 

 void abrir();
/*  Functions to be coded
int menu();
int menu2(); //manutencao de clientes
void adicionar();
void alterar();
void excluir();
void exibir();
void pesquisar(); */

main()
{
    system("cls");
    abrir();
    //menu();
}

void abrir() //open the csv file and copy it to 
{
    /* FileStream for the Library File */
    FILE *pFile;

    /* allocation of the buffer for every line in the File */
    char *buf = malloc(MAX_STR_LEN);
    char *tmp; 

    /* if the space could not be allocated, return an error */
    if (buf == NULL) {
        printf ("No memory\n");
            }

    if ( ( pFile = fopen( "control.csv", "r" ) ) == NULL ) //Reading a file
    {
        printf( "File could not be opened.\n" );
    }

    int i = 0;
    while (fgets(buf, 255, pFile) != NULL)
    {
        if ((strlen(buf)>0) && (buf[strlen (buf) - 1] == '\n')) //checa leitura
            buf[strlen (buf) - 1] = '\0';       

        tmp = strtok(buf, ";"); 
        cliente[i].id = atoi(tmp); //atoi for int

        tmp = strtok(NULL, ";"); //use strcpy for char
        strcpy(cliente[i].nome,tmp);

        tmp = strtok(NULL, ";");
        strcpy(cliente[i].endereco, tmp);

        tmp = strtok(NULL, ";");
        strcpy(cliente[i].cidade, tmp);

        tmp = strtok(NULL, ";");
        strcpy(cliente[i].pais, tmp);

        tmp = strtok(NULL, ";");
        strcpy(cliente[i].cep, tmp);

        tmp = strtok(NULL, ";");
        strcpy(cliente[i].nasc, tmp);

        tmp = strtok(NULL, ";");
        strcpy(cliente[i].telefone, tmp);

        tmp = strtok(NULL, ";");
        strcpy(cliente[i].total, tmp);

        //tempBook.ID = atoi(buf); fix below
        printf("%i, %s, %s, %s, %s, %s, %s, %s, %s \n",i, cliente[i].id , cliente[i].nome, cliente[i].endereco, cliente[i].cidade, cliente[i].pais, cliente[i].cep, cliente[i].nasc, cliente[i].telefone, cliente[i].total);

        i++;
    }
    //free(buf);
    fclose(pFile);
}

How can I solve this problem? I can't successfully copy the data from 100 clients in the csv to a structure.

Thank you since now!

Upvotes: 0

Views: 126

Answers (1)

Jabberwocky
Jabberwocky

Reputation: 50831

There are three main problems here:

  1. The format string in printf("%i, %s, %s, %s, ...) doesn't match the parameters, you need one more %i: printf("%i, %i, %s, %s, %s, ...).

  2. In your code you never call abrir() but you call menu(), which doesn't exist, therefore your code doesn't even compile.

  3. If you are on Windows (and only then) you need fopen(..., "rt")) instead
    of fopen(..., "r"))

Furthermore (not causing actual problems in your code):

char *buf = malloc(MAX_STR_LEN); can be replaced by char buf[MAX_STR_LEN];. It's pointless to allocate memory dynamically if the amount of memory is known at compile time. In that case you must of course not call free(buf) (which is commented out anyway).

Following declarations just after struct estrutura cliente[200]; are useless, you can remove them.

FILE *pFile;

//allocate buffer in each line

char *buf = (char*)malloc(MAX_STR_LEN);
char *tmp;

Otherwise the program should work fine unless your input file has fields that are larger than the field in your struct estrutura.

Upvotes: 1

Related Questions