Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void textToMatrix(FILE* file, long double *** dest, int* dataRows, int* dataCols){
char delim = ' '; //change for different delimiter
char buf[1024]; //buffer for fgets
printf("Reading File... \n");
char* line = fgets(buf, 1024, file);
// find number of columns of data
int cols = 0;
char *tmp = line; //SHALLOW copy of line
printf("Calculating number of columns... ");
while(*tmp == ' ') { //move over initial white space
tmp++;
}
while(*tmp != '\0') {
if(*tmp == delim){
cols++;
while( *tmp == delim){ //skip extra delimeters
tmp++;
}
} else {
tmp++;
}
}
printf("done! \n");
printf(" cols: %i\n",cols);
// Populate matrix with data from file
printf("Populating matrix with data... \n\n");
long double** data = (long double**)malloc(sizeof(long double *));
int rLen = 0; //Number of rows in data matrix
while( line != NULL) {
//make new row
rLen++;
data = (long double**)realloc(data,rLen*sizeof(long double*));
data[rLen-1] = (long double*)calloc(cols,sizeof(long double));
//populate with data
char** endptr = &line;
for(int i = 0; i<cols; ++i) {
data[rLen-1][i] = (long double)strtod(line, endptr);
//printf("%5f ",data[rLen-1][i]);
}
//printf("\n");
line = fgets(buf,1024,file);
}
printf("done! \n");
printf("rLen: %d\n", rLen);
printf("cols: %d\n", cols);
*dataRows = rLen;
*dataCols = cols;
*dest = data;
}
int main() {
FILE* file = fopen("test.txt","r");
long double** data;
int rows;
int cols;
textToMatrix(file, &data, &rows, &cols);
fclose(file);
printf("rows: %d, cols: %d\n",rows, cols);
for(int i=0; i<rows; ++i) {
for(int j=0; j<cols; ++j) {
printf("%1f ",data[i][j]);
}
free(data[i]);
printf("\n");
}
free(data);
getchar();
return 0;
}
well, that's it start to finish (no, there's no header file, bad me)