Read .CSV file in C

后端 未结 5 1084
温柔的废话
温柔的废话 2020-11-22 10:15

I Have a .csv file :

lp;imie;nazwisko;ulica;numer;kod;miejscowosc;telefon;email;data_ur
1;Jan;Kowalski;ul. Nowa;1a;11-234;Budry;123-123-456;jan@go.xxx;1980.         


        
5条回答
  •  星月不相逢
    2020-11-22 10:36

    Thought I'd share this code. It's fairly simple, but effective. It parses comma-separated files with parenthesis. You can easily modify it to suit your needs.

    #include 
    #include 
    #include 
    
    
    int main(int argc, char *argv[])
    {
      //argv[1] path to csv file
      //argv[2] number of lines to skip
      //argv[3] length of longest value (in characters)
    
      FILE *pfinput;
      unsigned int nSkipLines, currentLine, lenLongestValue;
      char *pTempValHolder;
      int c;
      unsigned int vcpm; //value character marker
      int QuotationOnOff; //0 - off, 1 - on
    
      nSkipLines = atoi(argv[2]);
      lenLongestValue = atoi(argv[3]);
    
      pTempValHolder = (char*)malloc(lenLongestValue);  
    
      if( pfinput = fopen(argv[1],"r") ) {
    
        rewind(pfinput);
    
        currentLine = 1;
        vcpm = 0;
        QuotationOnOff = 0;
    
        //currentLine > nSkipLines condition skips ignores first argv[2] lines
        while( (c = fgetc(pfinput)) != EOF)
        {
           switch(c)
           {
              case ',':
                if(!QuotationOnOff && currentLine > nSkipLines) 
                {
                  pTempValHolder[vcpm] = '\0';
                  printf("%s,",pTempValHolder);
                  vcpm = 0;
                }
                break;
              case '\n':
                if(currentLine > nSkipLines)
                {
                  pTempValHolder[vcpm] = '\0';
                  printf("%s\n",pTempValHolder);
                  vcpm = 0;
                }
                currentLine++;
                break;
              case '\"':
                if(currentLine > nSkipLines)
                {
                  if(!QuotationOnOff) {
                    QuotationOnOff = 1;
                    pTempValHolder[vcpm] = c;
                    vcpm++;
                  } else {
                    QuotationOnOff = 0;
                    pTempValHolder[vcpm] = c;
                    vcpm++;
                  }
                }
                break;
              default:
                if(currentLine > nSkipLines)
                {
                  pTempValHolder[vcpm] = c;
                  vcpm++;
                }
                break;
           }
        }
    
        fclose(pfinput); 
        free(pTempValHolder);
    
      }
    
      return 0;
    }
    

提交回复
热议问题