Skip to content

Instantly share code, notes, and snippets.

@quxiaofeng
Forked from amirmasoudabdol/read_csv.c
Created April 18, 2019 05:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save quxiaofeng/56b5785a76eb8063a2deb5e72f5f8f08 to your computer and use it in GitHub Desktop.
Save quxiaofeng/56b5785a76eb8063a2deb5e72f5f8f08 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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment