Skip to content

Instantly share code, notes, and snippets.

@amirmasoudabdol
Created May 19, 2014 09:59
Show Gist options
  • Select an option

  • Save amirmasoudabdol/f1efda29760b97f16e0e to your computer and use it in GitHub Desktop.

Select an option

Save amirmasoudabdol/f1efda29760b97f16e0e to your computer and use it in GitHub Desktop.
To read the CSV file in C
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void read_csv(int row, int col, char *filename, double **data){
FILE *file;
file = fopen(filename, "r");
int i = 0;
char line[4098];
while (fgets(line, 4098, file) && (i < row))
{
// double row[ssParams->nreal + 1];
char* tmp = strdup(line);
int j = 0;
const char* tok;
for (tok = strtok(line, "\t"); tok && *tok; j++, tok = strtok(NULL, "\t\n"))
{
data[i][j] = atof(tok);
printf("%f\t", data[i][j]);
}
printf("\n");
free(tmp);
i++;
}
}
int main(int argc, char const *argv[])
{
/* code */
if (argc < 3){
printf("Please specify the CSV file as an input.\n");
exit(0);
}
int row = atoi(argv[1]);
int col = atoi(argv[2]);
char fname[256]; strcpy(fname, argv[3]);
double **data;
data = (double **)malloc(row * sizeof(double *));
for (int i = 0; i < row; ++i){
data[i] = (double *)malloc(col * sizeof(double));
}
read_csv(row, col, fname, data);
return 0;
}
@angysinghdhillon

Copy link
Copy Markdown

where and how do i mention the file name

@manoharmukku

manoharmukku commented Jul 18, 2018

Copy link
Copy Markdown

You need to pass the file name as the command line argument while running the program.
For example
./a.out 500 15 data_file.csv
where a.out is the executable, 500 is the number of rows, 15 is the number of columns and data_file.csv is the file name which is present in the current directory.

@divyangarora1

Copy link
Copy Markdown

This code is reading only one row .

@tomasrojasc

Copy link
Copy Markdown

indeed is reading only one row and filling the rest with zeros. Did someone managed to finish the function?

@kiviodepaula

kiviodepaula commented Mar 1, 2021

Copy link
Copy Markdown

The code it's working fine, but you need to customize it according your csv file. In my case, the values were separeted by ",", so I needed to change the code as follow:

for (tok = strtok(line, ","); tok && *tok; j++, tok = strtok(NULL, ","))

@lou8085

lou8085 commented Jun 9, 2021

Copy link
Copy Markdown

Very helpful program. Thank you !!

@Willespinosa13

Willespinosa13 commented Jun 21, 2021

Copy link
Copy Markdown

Thank you @manoharmukku.
the code is run using linux, right?

@lou8085

lou8085 commented Jun 21, 2021

Copy link
Copy Markdown

I ran it under Windows 10 using gcc

@manoharmukku

Copy link
Copy Markdown

Thank you @manoharmukku.
the code is run using linux, right?

The code can be run in any command line (terminal) which has gcc. It works for Linux, MacOS and Windows.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment