Skip to content

Instantly share code, notes, and snippets.

@Lif3line
Created July 25, 2014 15:00
Show Gist options
  • Save Lif3line/38fc78bd6d6d20646a8d to your computer and use it in GitHub Desktop.
Save Lif3line/38fc78bd6d6d20646a8d to your computer and use it in GitHub Desktop.
Short C program that takes in a runtime defined CSV file and outputs a 1D const array version as a single line. Useful for generating look up tables from CSVs essentially.
#include <stdio.h>
#include <stdlib.h>
int main() {
char c, inFileName[100], outFileName[100], type[20], arrayName[50];
FILE *fin, *fout;
int position;
printf("CSV to 1D lookup table suitable for use in C/C++ v0.1\n");
printf("Prints out to a file as a single line even if CSV is multiline\n\n");
printf("Enter the name of the csv you want to use (don't worry about .csv)\n");
printf("NOTE: csv is assumed to be all data no gaps\n");
gets(inFileName);
strcat(inFileName, ".csv");
fin = fopen(inFileName,"r"); // Read Only
if(fin == NULL) {
perror("Error while opening the file:\n");
exit(EXIT_FAILURE);
}
printf("Enter full output file name (including extension). WARNING will overwrite.\n");
gets(outFileName);
fout = fopen(outFileName,"w+"); // Write Only
if(fout == NULL) {
perror("Error while opening the file:\n");
exit(EXIT_FAILURE);
}
printf("Enter array type: int,double,float etc\n");
gets(type);
printf("Enter desired array name\n");
gets(arrayName);
printf("Construction in progress..");
fprintf(fout,"const %s %s%s",type,arrayName, "[] = {");
while((c = fgetc(fin)) != EOF) {
if(c == '\n') {
fprintf(fout,"%s",",");
} else {
fprintf(fout,"%c",c);
}
}
position = ftell(fout) - 1; // Go back one entry to remove traielr comma
fseek(fout,position,SEEK_SET);
fprintf(fout,"%s","};");
fclose(fin);
fclose(fout);
printf("Construction Complete\n");
system("PAUSE");
return EXIT_SUCCESS;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment