john pfeiffer
  • Home
  • Categories
  • Tags
  • Archives

file remove baddata

/* john pfeiffer 21jan07    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] = '\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;
}

  • « httpgetv3
  • ftp client in c »

Published

Jan 21, 2007

Category

c

~164 words

Tags

  • baddata 2
  • c 95
  • file 92
  • remove 16