2 years ago

#75673

test-img

Austin M

Loading csv file into datatable in c

Hi how can I load the content of a comma-separated values (csv) file into an initialized DataTable. Using a ‘\’ to escape commas (‘,’).And what shall I call in the main to output?

Another question how can a datatable be initialized? This is the code that I tried:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "Functions.h"

struct Datatable_t ;
     void loadDT(Datatable_t *table_data){
        //int
        FILE *fp = fopen("test.csv", "r");
        if (!fp) {
            printf("Error occured");
        }
        char buff[1024]; //stores the first 1024 lines into buff
        int row_count = 0;
        int field_count = 0;

        Datatable_t values[999];

        int i = 0;
        while (fgets(buff, 1024, fp)) {
            field_count = 0;
            row_count++;

            char *field = strtok(buff, ",");
            while (field) {
                if (row_count == 1)
                    strcpy(table_data->labels[MAX_X][i], field);
                i++;

                field = strtok(NULL, ",");
                field_count++;
            }
            i++;
        }
        fclose(fp);
    }

This is the code for the header file.

#define X 6
#define Y 6


typedef struct datatable{
    //char labels[6][64];
    char labels[1][X][64];
    float floating_numbers[X][Y];
    char string_values[X][Y][63];

}Datatable_t;//variable

Datatable_t *initDT(size_t size);
void definitDT(Datatable_t *datatable);
void loadDT(Datatable_t *table_data);

Thanks for any help.

c

clion

0 Answers

Your Answer

Accepted video resources