vendredi 11 décembre 2015

How to read a text file line by line and insert it into sqlite database using c programming and in each line in my text file contains ','

  /*Here is the code and in text file data is like
                          255,40001,coil,temp,
                          255,40002,register,Pressure    */  
#include <stdio.h>
    #include <string.h>
    #include <sqlite3.h>
    int main ( void )
    {
       sqlite3 *db;
       char *zErrMsg = 0;
       int  rc;
       char *sql;
       char sql1[100];
       char str2[50];
       char str3[50];
       char str4[50];
       char str5[50];
       char * pch;

       rc = sqlite3_open("sample2.db", &db);
       if( rc ){
          fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
          return 1;
       }else{
          fprintf(stdout, "Opened database successfully\n");
       }


       static const char filename[] = "modbus.ini";
       FILE *file = fopen ( filename, "r" );
       if ( file != EOF )
       {
          char line [ 128 ]; /* or other suitable maximum line size */
          while ( fgets ( line, sizeof line, file ) != NULL ) /* read a line */
          {

             printf("%s\n",line);
             //pch = strtok (line,",");
             //printf("%s\n",pch);
             sprintf(sql1,"INSERT INTO config_ini(deviceid,mod_add,param_type,modbus_type) VALUES('%s','%s','%s','%s')",line[0],line[1],line[2],line[3]);
             rc = sqlite3_exec(db, sql1, 0, 0, &zErrMsg);



             // fputs ( line, stdout ); /* write the line */
          }
          fclose ( file );
       }
       else
       {
          perror ( filename ); /* why didn't the file open? */
       }
       return 0;
    }

How to do this???Can anybody can know?? Here is the texy file:

255,40001,temperature,coil
255,40002,Pressure,coil
255,40003,Humidity,coil
255,40004,Co2,coil
255,40005,temperature,hreg
255,40006,Pressure,hreg
255,40007,Humidity,hreg
255,40008,Co2,hreg
255,40009,temperature,ireg
255,400010Pressure,ireg
255,400011,Humidity,ireg
255,400012,Co2,ireg
255,400013,temperature,discret_input
255,400014,Pressure,discret_input
255,400015,Humidity,discret_input
255,400015,Co2,discret_input

Aucun commentaire:

Enregistrer un commentaire