Write in C

The last couple of months has been all about Calculus, Agorithms and Datastructures, Data modelling with Object Role Modelling and SQL.

After finally getting familiar with the basics of PostgreSQL I found myself curious about using the MySQL databases supplied by my web hosting service, and today I got around to making a program to insert .csv files (with whitespace as delimiter) into my own tables.

As an added challenge I thought I’d use C rather than Java, which means I had to use sscanf instead of split to collect individual integers from an input file separated by whitespace.

This bit of code reads an input file, calculates the size of the file, the number of rows and columns and then proceeds to read the entire file. It then uses sscanf to collect each integer now that we know the number of rows and columns and then creates an sql script based on that information.

There’s probably an easier way of doing this, but in my experience, always looking for shortcuts takes time, so I might as well just use what I know already to get the job done:

 


#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
#define max(a, b) ((a) > (b) ? (a) : (b))
#define pline printf("\n")

void tsize(char filename[], int ans[]);

int main(int argc, char *argv[]) {
if(argc < 4) {
   printf("too few arguments");
   return -1;
}
char *typename = argv[3];
int tablesize[4];
bzero(tablesize, sizeof(int) * 4);
tsize(argv[1], tablesize);
int row, col, i, q, inp, siz, pos, totalpos;
row = col = i = q = inp = siz = pos = totalpos = 0;
col = tablesize[0];
row = tablesize[1];
siz = tablesize[2];
int table[row][col];
FILE *in = fopen(argv[1], "r");
char *text = malloc(sizeof(char) * siz);
bzero(text, sizeof(char) * siz);
while((inp = fgetc(in)) != EOF) {
   text[i++] = inp;
}
fclose(in);
for(i = 0; i < row; i++) {
   for(q = 0; q < col; q++) {
      int val = 0;
      sscanf(text + totalpos, "%d%n", &val, &pos);
      totalpos += pos;
      table[i][q] = val;
}
}
FILE *out = fopen(argv[2], "w");
fprintf(out, "CREATE TABLE rammepris (\n");
fprintf(out, "meterpris INT NOT NULL,\n");
fprintf(out, "halvmaal INT NOT NULL,\n");
fprintf(out, "utpris INT NOT NULL,\n");
fprintf(out, "rammetype VARCHAR NOT NULL UNIQUE,\n");
fprintf(out, "PRIMARY KEY(meterpris, halvmaal)\n");
fprintf(out, ");\n");
for(i = 1; i < row; i++) {
   for(q = 1; q < col; q++) {
      int meterpris = table[i][0];
      int halvmaal = table[0][q];
      fprintf(out, "INSERT INTO rammepris(meterpris, halvmaal, utpris, rammetype) \   
      values(%d, %d, %d, %s);\n", meterpris, halvmaal, table[i][q], typename);
   }
}
fclose(out);
}

void tsize(char filename[], int ans[]) {
FILE *in = fopen(filename, "r");
int col, inp, siz;
col = inp = siz = 0;
while((inp = fgetc(in)) != EOF) {
   ans[2]++;
   if(inp == ' ' || inp == '\n')
      col++;
   if(inp == '\n') {
      ans[0] = max(col, ans[0]);
      col = 0;
      (ans[1])++;
   }
}
fclose(in);
}

Click Here