read-csv.c (1350B)
1 #include <stdio.h> 2 #include <stdlib.h> 3 4 #define TRUE 1 5 #define FALSE 0 6 7 8 int getRows(char* fileName){ 9 char c; 10 int count = 0; 11 FILE* fp = fopen(fileName, "r"); 12 while((c = getc(fp)) != EOF){ 13 if(c == '\n'){ 14 count += 1; 15 } 16 } 17 return count + 1; 18 19 } 20 21 // there's more too it than just this 22 // not sure how \n characters work. 23 // not sure how to handle cases where escaping for \" charcter. 24 25 int getColumns(char* fileName){ 26 char c; 27 int count = 0; 28 int escaped = FALSE; 29 30 FILE* fp = fopen(fileName, "r"); 31 c = getc(fp); 32 while(c != EOF && c != '\n'){ 33 if(c == ',' && escaped == FALSE){ 34 count += 1; 35 } 36 else if (c == '"'){ 37 if (escaped == TRUE){ 38 escaped = FALSE; 39 } 40 else{ 41 escaped = TRUE; 42 } 43 } 44 c = getc(fp); 45 } 46 47 if(escaped == TRUE){ 48 return -1; 49 } 50 return count + 1; 51 } 52 53 54 int main(int argc, char** argv){ 55 56 char* fileName = argv[1]; 57 FILE* fp = fopen(fileName, "r"); 58 59 char** allRecords; 60 int rows = getRows(fileName); 61 int columns = getColumns(fileName); 62 63 if (columns == -1){ 64 printf("Non-matching quotations in first row."); 65 } 66 67 printf("Rows: %d, Columns: %d\n", rows, columns); 68 69 fclose(fp); 70 71 return 0; 72 }