D
Disc Magnet
I wrote a simple C program to read the following CSV file:
a.csv:
1,2,3 4,5
10,20,30,40,50
100,200,300,400,500
Code:
#include <stdio.h>
#include <stdlib.h>
#define ROWS 3
#define COLS 5
int main()
{
FILE *fp;
int csv[ROWS][COLS];
int i, j;
if ((fp= fopen("a.csv", "r")) == NULL) {
fprintf(stderr, "Error opening file.");
exit(1);
}
for (i = 0; i < ROWS; i++)
for (j = 0; j < COLS; j++)
fscanf(fp, "%d,", &csv[j]);
fclose(fp);;
for (i = 0; i < ROWS; i++) {
for (j = 0; j < COLS; j++)
printf("%d ", csv[j]);
printf("\n");
}
}
Note, that the fscanf call is expecting an integer to be followed by a
comma everywhere. But the last integer in every line of the CSV file
is not followed by a comma. But, I still get the output perfectly well
for all integers.
Could someone please explain why the fscanf() function doesn't fail
when it doesn't find a comma after the last integer of every line? I
would appreciate if someone can explain or point me to the precise
rules involved in this.
a.csv:
1,2,3 4,5
10,20,30,40,50
100,200,300,400,500
Code:
#include <stdio.h>
#include <stdlib.h>
#define ROWS 3
#define COLS 5
int main()
{
FILE *fp;
int csv[ROWS][COLS];
int i, j;
if ((fp= fopen("a.csv", "r")) == NULL) {
fprintf(stderr, "Error opening file.");
exit(1);
}
for (i = 0; i < ROWS; i++)
for (j = 0; j < COLS; j++)
fscanf(fp, "%d,", &csv[j]);
fclose(fp);;
for (i = 0; i < ROWS; i++) {
for (j = 0; j < COLS; j++)
printf("%d ", csv[j]);
printf("\n");
}
}
Note, that the fscanf call is expecting an integer to be followed by a
comma everywhere. But the last integer in every line of the CSV file
is not followed by a comma. But, I still get the output perfectly well
for all integers.
Could someone please explain why the fscanf() function doesn't fail
when it doesn't find a comma after the last integer of every line? I
would appreciate if someone can explain or point me to the precise
rules involved in this.