Below is a program in C that I am trying to use to read in a spreadsheet (in CSV form), which I will eventually be doing calculations on and then writing out to a new file. I'm currently trying to figure out the following three things:
1) How to make it so that the matrix is dynamically allocated memory. Right now it's set to be 10 x 10, but I want it to read the number of items between comma's as the width and the number of rows as the height. Can I just add the number of occurences of commas and add 1 to the total to get the width?
2) Right now it just writes out the data that it's reading in from the file, but could someone point me in the right direction for writing to a new CSV file with the - eventually modified - data?
3) I want to work with floating point numbers to two spaces (i.e. 10.14), where should I be defining that? I tried "float array[10][10] and a few other things, but wasn't too successful.
I'm pretty new to C, and these forums have been a huge help so far, thanks to everyone who's contributed to any of the threads.
#include <stdio.h>
#include <stdlib.h>
#define ARRAYSIZE(x) (sizeof(x)/sizeof(*(x)))
int main(void)
{
const char filename[] = "file.csv";
/* Open the file */
FILE *file = fopen(filename, "r");
if (file)
{
/* Need dynamic allocation here */
float array[10][10];
size_t i, j, k;
char buffer[BUFSIZ], *ptr;
/* Read each line from the file */
for(i=0; fgets(buffer, sizeof buffer, file); i++)
{
/* Parse the comma-seperated values from each line into 'array' */
for(j=0, ptr=buffer; j < ARRAYSIZE(*array); ++j, ++ptr)
{
array[i][j] = (int)strtol(ptr, &ptr, 10);
}
}
fclose(file);
/* Print the data in 'array' */
for(j = 0; j < i; ++j)
{
printf("array[%lu]:", (long unsigned)j);
for(k = 0; k < ARRAYSIZE(*array); ++k)
{
printf("%4d", array[j][k]);
}
putchar('\n');
}
}
else
{
perror(filename);
}
system("pause");
return 0;
}
Sample data I'm using:
2018,015,110.87,110.9,110.87,110.9,9,9,9,9
2018,020,110.9,110.9,110.86,110.88,5,5,5,5
20,025,110.87,110.88,110.85,110.88,7,7,7,7
2018,030,110.88,110.95,110.87,110.93,10,10,10,10
18,035,110.93,110.94,110.91,110.92,9,9,9,9
20,040,110.92,110.93,110.9,110.91,11,11,11,11
218,045,110.91,110.93,110.91,110.91,6,6,6,6
20218,050,110.91,110.93,110.9,110.9,10,10,10,10
218,055,110.9,110.93,110.9,110.92,11,11,11,11
20218,100,110.89,110.93,110.9,110.94,12,12,12,12
Thanks for any help!
Nolan