/* john pfeiffer 21jan08, update 17feb08 removed extra line spaces (/n)
remove bad data (more/less than 6 comma in a csv file)
Name,Email,Company,Phone,Updates,Document,Time
baddata.c.exe input is datasheets.csv, outputs: good-data.csv, bad-data.csv
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define FIELD_MAX 256 /* each column (field) can have up to 256 chars */
#define COLUMNS_MAX 32 /* up to 32 columns in case there is bad data */
int main( int argc, char* argv[])
{
char linebuffer[FIELD_MAX * COLUMNS_MAX];
int comma_counter=0;
int i=0;
char c;
FILE* ifp;
FILE* ofpGood;
FILE* ofpBad;
ifp = fopen("datasheets.csv","r");
ofpGood = fopen("good-data.csv","w");
ofpBad = fopen("bad-data.csv","w");
if(ifp == NULL)
{ printf("error opening input file!");
getchar();
exit(1); }
if( (ofpGood == NULL) || (ofpBad == NULL) )
{ printf("error opening output file!");
getchar();
exit(1); }
printf("%s is creating 'good-data.csv' and 'bad-data.csv\n",argv[0]);
i=0;
c = getc(ifp);
while( c != EOF )
{
if( c == '\n' )
{
linebuffer[i-1] = '\0'; /* must be null terminated for fputs */
if( comma_counter == 6)
{ fputs(linebuffer,ofpGood);
}else
{ fputs(linebuffer,ofpBad); }
comma_counter = 0; /* reset the comma counter for the next line */
i=0; /* reset the buffer */
}
else if( c == ',' )
{ comma_counter++;
}
linebuffer[i] = c;
c = getc( ifp ); /* continue the loop */
i++;
}/* end while - finished file*/
fclose(ifp);
fclose(ofpGood);
fclose(ofpBad);
return 0;
}