I've been struggling with this program for a long time. The goal is to read a simple .csv file without using libcsv. After researching and programming I've come up with this implementation. It's almost there but it fails just at the end.
I suspect the error is in the line with str2uint64_t(ptr, &int64_converted, &error);
but I can't figure out why.
In case it might help, I've adapted this implementation from the one I've found in this web page: https://cboard.cprogramming.com/c-programming/47105-how-read-csv-file.html
By the way, the program can be compiled and called as:
gcc -o q q.c && ./q file.csv
Where file.csv
might be something like:
0,10,20,300,905
55,18,8,253,65
0,18,265,293,98
23,18,28,6675,86
677,20,28,293,100
The implementation:
#include <stdio.h>
#include <stdlib.h>
#include <inttypes.h>
#include <errno.h>
void str2uint64_t(const char *str, uint64_t *intConverted, int *error)
{
// Converts string to uint64_t
*intConverted = 0;
*error = 0;
const char *s = str;
int sign = *s;
char *end;
errno = 0;
const uint64_t sl = strtoull(str, &end, 10);
if (end == str)
{
//fprintf(stderr, "%s: not a decimal number\n", str);
*error = 1;
}
else if ('\0' != *end)
{
//fprintf(stderr, "%s: extra characters at end of input: %s\n", str, end);
*error = 1;
}
else if (ERANGE == errno)
{
//fprintf(stderr, "%s out of range of type uint64_t\n", str);
*error = 1;
}
else if (sign == '-')
{
//fprintf(stderr, "%s negative\n", 0);
//errno = ERANGE;
*error = 1;
}
//return sl;
*intConverted = sl;
}
void *newMatrix(size_t rows, size_t cols)
{
return malloc (sizeof(uint64_t[rows][cols]));
}
void importMatrix(char CSVFilePath[], size_t rows, size_t cols, uint64_t matrix[rows][cols])
{
size_t i, j;
uint64_t int64_converted;
int error = 0;
FILE *CSVfile = fopen(CSVFilePath, "r");
if (CSVfile == NULL)
{
perror("Error");
exit(EXIT_FAILURE);
}
char buffer[BUFSIZ], *ptr;
for (i = 0; fgets(buffer, sizeof buffer, CSVfile); ++i)
{
for (j = 0, ptr = buffer; j < rows; ++j, ++ptr)
{
str2uint64_t(ptr, &int64_converted, &error);
if (error == 0)
{
// From https://cboard.cprogramming.com/c-programming/47105-how-read-csv-file.html >> array[i][j] = (int)strtol(ptr, &ptr, 10);
matrix[i][j] = int64_converted;
}
else
{
printf("Failed to import matrix\n");
exit(0);
}
}
}
fclose(CSVfile);
putchar('\n');
}
int main(int argc, char *argv[])
{
if (argc < 2)
{
fprintf(stderr, "Usage: ./<program> <file.csv>\n");
exit(EXIT_FAILURE);
}
size_t rows = 5;
size_t cols = rows;
uint64_t (*matrix)[rows] = newMatrix(rows, cols);
importMatrix(argv[1], rows, cols, matrix[rows][cols]);
//////////////////////////////
return 0;
}