Hi all,

I'd posted this problem previously but in the wrong place..:)..Hopefully, I can get the answer from this thread. I'm a newbie in C..Right now, I have to write a code to read a text file and then insert all the info inside that text file into database. Should anyone have a simple sample of it, maybe you can share with me in order for me to learn on how to do it.

Thanks in advance

Hi all,

I'd posted this problem previously but in the wrong place..:)..Hopefully, I can get the answer from this thread. I'm a newbie in C..Right now, I have to write a code to read a text file and then insert all the info inside that text file into database. Should anyone have a simple sample of it, maybe you can share with me in order for me to learn on how to do it.

Thanks in advance

// reading a text file
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main () {
  string line; //this will contain the data read from the file
  ifstream myfile ("example.txt"); //opening the file.
  if (myfile.is_open()) //if the file is open
  {
    while (! myfile.eof() ) //while the end of file is NOT reached
    {
      getline (myfile,line); //get one line from the file
      cout << line << endl; //and output it
    }
    myfile.close(); //closing the file
  }
  else cout << "Unable to open file"; //if the file is not open output <--

  return 0;
}

I don't really get what you mean by sending it to a database, but this is the file-reading part


Greetz, Eddy


EDIT:
Oh wait, you sayd "C", did you mean C or C++? If it's C above code probably won't work.
If you're really doing C then I suggest you switch to C++ anyway ;)

Hi Eddy,

Yerp, I need to write that code in C...n what I meant by sending it to database is that, I have 1 text file to be read, n after that, this program need to insert all the read data from that file into database. Actually, I've got that text file from other people and I need to insert that data into database so that, I can use it for my program..

Thanks

I still don't really get what you mean with the database. Is it an SQL database you need to put it to (or another type of database)? Or do you just mean an array(table) inside your own program?


Greetz, Eddy

Hi Eddy,

Actually, I want to read the file and then extract the content of the file to be inserted into the database (MySQL database). I had created a table in MySQL so that, when this C program run, it can read as well as inserting the content to that table created.
Hope you can get what I mean..:)

Thanks a lot

you will have to

1) learn SQL database language -- SELECT, INSERT and UPDATE are three most commonly used SQL functions.

2) learn how to use ODBC to access the database from C, C++ or most any other computer language. Here is a short tutorial to get you started.

And here are a lot of other links.

Hi all,

Basically, I have done my code and it already successfully read the text file n insert the content into the database. But the problem is..i dunt know how to write a code so that, this program can read other files at the same time.Meaning that, I dunt want the filename to be hard coded because I'll receive 4 files to be read every hour.
Below is the code:

#include <stdio.h>
#include <string.h>
#include <mysql.h>

#define HOST "localhost"
#define USER ""
#define PASSWD ""
#define DB_NAME ""

void readLogFile();
void insert2DB(); 
void logSeparator(char log[1600]);
void logSeparatorDetails(char logDetails[2500]);
void date2DB(char dateLog[20]);
//int operatorPrefix();

static MYSQL demo_db;
char string1[150], msg[250];
char date[50],time[50],noXXX[50],hpno[50],noYYY[50];
char dateLog[20];
char dd[20], mm[20], yyyy[20], theDate[20];
    
int main()
{
    readLogFile();
}

void readLogFile()
{
    char line[1600];
    FILE *fp;

    fp=fopen("DB1-12-27-07-2006.txt", "r+");

    if(fp==NULL) {
        printf("file not found!\n");
        exit(0);
    }
    else {
        while(!feof(fp)) {
            bzero(line, sizeof(line));
            fgets(line,1600,fp);
            logSeparator(line);
            logSeparatorDetails(string1);
            date2DB(date);
            //operatorPrefix();
            insert2DB();
        }
    }

    fclose(fp);
    return;
}

void insert2DB()
{
    char query[16384];
    char query1[16384];
    int stat;

    if(!mysql_connect(&demo_db, HOST, USER, PASSWD))
      {
            printf(mysql_error(&demo_db));
            exit(1);
      }

      if(mysql_select_db(&demo_db, DB_NAME))
      {
            printf(mysql_error(&demo_db));
            exit(1);
      }

    bzero(query, sizeof(query1));
    sprintf(query, "INSERT INTO PostpaidProfile2 (MobileNumber,PackagePlan,Status) VALUES('%s','%s',1)",hpno,msg,stat);

    printf("%s\n",query);

    if(mysql_real_query(&demo_db, query, strlen(query)+255))
      {
           printf(mysql_error(&demo_db));
            bzero(query, sizeof(query));
             exit(1);
      }

    mysql_close(&demo_db);

    return;
}

void logSeparator(char log[2000])
{
    char *temp, msgTemp[200];
    int io;

    io=0;
    bzero(string1, sizeof(string1));
    bzero(msg, sizeof(msg));

    temp = strtok (log," ");
       
    while (temp != NULL)
        {    
            io++;
                        
                switch(io)
                {
                    case 1: 
                            strcpy (string1, temp);
                                break;
                    default: 
                              strcpy (msgTemp, temp);
                              if (strlen(msg) != 0) {
                                  strcat(msg," ");
                                }
                                strcat(msg,msgTemp);
                                break;
        }
                          
                temp = strtok (NULL," ");
    }
}

void logSeparatorDetails(char logDetails[2000])
{
    char *temp2;
    int io2;

    io2=0;
    bzero(hpno, sizeof(hpno));
    bzero(msg, sizeof(msg));

    temp2 = strtok (logDetails,",");
       
    while (temp2 != NULL)
        {    
            io2++;
                        
                switch(io2)
                {
                
                    case 1: 
                            strcpy (hpno, temp2);
                                break;
                    case 2: 
                            strcpy (msg, temp2);
                                break;
                
        }
                          
                temp2 = strtok (NULL,",");
    }
}

void date2DB(char dateLog[20])
{
    bzero(dd, sizeof(dd));    
    bzero(mm, sizeof(mm));
    bzero(yyyy, sizeof(yyyy));
    bzero(theDate, sizeof(theDate));
    
        strncpy(dd,dateLog,2);
        strncpy(mm,dateLog+2,2);
        strncpy(yyyy,dateLog+4,4);
        
        strcat(theDate,yyyy);
        strcat(theDate,"-");
        strcat(theDate,mm);
        strcat(theDate,"-");
        strcat(theDate,dd);   //convert to yyyy-mm-dd as in mysql date format   

    return;
}

Thanks

change readLogFile() so that you can pass the filename into it. readLogFile( const char* filename) then you can call readLogFile for any file you want.

readLogFile("file1.txt");
readLogFile("file2.txt");

Hi WolfPack,

Refer to your given code, it's work but I still need to hardcode the filename. I want it to automatically read all the files received because I'll always receive files every hour and everyday.
:)

Thanks

Oh. Then search for passing Command Line Arguments in C/C++. By using Command Line arguments, you can pass the filename from the command line to your program.
Like this

C:\> YourProgram.exe filename

then you can call this program when you receive the file.

Hi WolfPack,

I've done like this:

int main()
{
    char filename[100];
    scanf("%s",&filename); 
    readLogFile(filename);
}

since i'm using scanf, so..I need to give the input to my .exe file. If possible, I want it to be auto run for reading n insert the contents into database. Is there any way that I can rewrite the code so that, It can automatically read any filename that coming in.

Thanks..:)

Change your program like this

int main(int argc, char *argv[])
{
    int i;
    if ( argc == 1 )
    {
            cout << "Enter at least one file name\n";
            return -1;
    }
    for (i = 1; i < argc; i++)
    {
          readLogFile(argv[i]);
     }
    return 0;
}

Now when you Run the program from the command line, type the program name and the filenames like this Program.exe Filename1.txt Filename2.txt ... the files will get processed. I hope that answers your question.

Hi WolfPack,

ok..I've got what do u mean..and I already try it n it works..but..I still need to type the filename right?..If possible, I just want to run program.exe only but then it can read all the files inside the same directory.

I just will run:

program.exe


Thanks...you already help me a lot...your help very much appreciated...

Hi WolfPack,

ok..I've got what do u mean..and I already try it n it works..but..I still need to type the filename right?..If possible, I just want to run program.exe only but then it can read all the files inside the same directory.

I just will run:

program.exe


Thanks...you already help me a lot...your help very much appreciated...

Yes, you still have to type the filename. There is no way to automatically get it done without making the program more complex. The best and easiest way to do is write a Command Script that executes your program for all the datafiles in the folder. What is your operating system?

Hi WolfPack,

oooo...ic..if that so, maybe I need to provide bash script to execute the program..im using OS Red Hat Linux...:)

Thanks...

Hi WolfPack,

ok..I've got what do u mean..and I already try it n it works..but..I still need to type the filename right?..If possible, I just want to run program.exe only but then it can read all the files inside the same directory.

This may not be necessary. If you use the filename *.fil, in the version of Unix I used the command line was expanded to include all .fil files. Then you only have to loop through the command line parameters if Red Hat works the same. Give it a try with something simple:

int main(int ac, char *av[])
{
    int parm=1;
    while (parn < ac)
    {
        puts(av[parm++]);
    }
    return 0;
}

See what happens. Add the headers, of course.


By the way, using scanf() to read strings is just like using gets() -- you should really us something safer like fgets().

This may not be necessary. If you use the filename *.fil, in the version of Unix I used the command line was expanded to include all .fil files. Then you only have to loop through the command line parameters if Red Hat works the same. Give it a try with something simple:

int main(int ac, char *av[])
{
    int parm=1;
    while (parn < ac)
    {
        puts(av[parm++]);
    }
    return 0;
}

hmm. Cool trick. pity it doesn't work in Windows too. By the way, I think this is a typo. while (par[B]n[/B] < ac) Edit:
Works in Cygwin. That is a consolation. :D

Hi All,

This is the code to read the text file:

#include <stdio.h>
#include <string.h>
#include <mysql.h>

#define HOST "localhost"
#define USER "yati"
#define PASSWD "yati"
#define DB_NAME "subscriberTool"

void readLogFile(const char* filename);
void insert2DB();
void logSeparator(char log[1600]);
void logSeparatorDetails(char logDetails[2500]);
void date2DB(char dateLog[20]);

static MYSQL demo_db;
char string1[150], msg[250];
char date[50],time[50],hpno[50];
char dateLog[20], filename[200];
char dd[20], mm[20], yyyy[20], theDate[20];
   
int main(int argc, char *argv[])
{
    int i;
    if ( argc == 1 )
    {
            return -1;
    }
    for (i = 1; i < argc; i++)
    {
          readLogFile(argv[i]);
     }
    return 0;
}

void readLogFile(const char* filename)
{
    char line[1600];
    FILE *fp;

    fp=fopen(filename, "r+");

    if(fp==NULL) {
        printf("file not found!\n");
        exit(0);
    }
    else {
        while(!feof(fp)) {
            bzero(line, sizeof(line));
            fgets(line,1600,fp);
            logSeparator(line);
            logSeparatorDetails(string1);
            date2DB(date);
            insert2DB();
        }
    }

    fclose(fp);
    return;
}

void insert2DB()
{
    char query[16384];
    char query1[16384];
    int stat;

    if(!mysql_connect(&demo_db, HOST, USER, PASSWD))
      {
            printf(mysql_error(&demo_db));
            exit(1);
      }

      if(mysql_select_db(&demo_db, DB_NAME))
      {
            printf(mysql_error(&demo_db));
            exit(1);
      }

    bzero(query, sizeof(query1));
    sprintf(query, "INSERT INTO PostpaidProfile2 (MobileNumber,PackagePlan,Status) VALUES('%s','%s',1)",hpno,msg,stat);

    printf("%s\n",query);

    if(mysql_real_query(&demo_db, query, strlen(query)+255))
      {
           printf(mysql_error(&demo_db));
            bzero(query, sizeof(query));
             exit(1);
      }

    mysql_close(&demo_db);

    return;
}

void logSeparator(char log[2000])
{
    char *temp, msgTemp[200];
    int io;

    io=0;
    bzero(string1, sizeof(string1));
    bzero(msg, sizeof(msg));

    temp = strtok (log," ");
      
    while (temp != NULL)
        {   
            io++;
                       
                switch(io)
                {
                    case 1:
                            strcpy (string1, temp);
                                break;
                    default:
                              strcpy (msgTemp, temp);
                              if (strlen(msg) != 0) {
                                  strcat(msg," ");
                                }
                                strcat(msg,msgTemp);
                                break;
        }
                         
                temp = strtok (NULL," ");
    }
}

void logSeparatorDetails(char logDetails[2000])
{
    char *temp2;
    int io2;

    io2=0;
    bzero(hpno, sizeof(hpno));
    bzero(msg, sizeof(msg));

    temp2 = strtok (logDetails,",");
      
    while (temp2 != NULL)
        {   
            io2++;
                       
                switch(io2)
                {
               
                    case 1:
                            strcpy (hpno, temp2);
                                break;
                    case 2:
                            strcpy (msg, temp2);
                                break;
               
        }
                         
                temp2 = strtok (NULL,",");
    }
}

void date2DB(char dateLog[20])
{
    bzero(dd, sizeof(dd));   
    bzero(mm, sizeof(mm));
    bzero(yyyy, sizeof(yyyy));
    bzero(theDate, sizeof(theDate));
   
        strncpy(dd,dateLog,2);
        strncpy(mm,dateLog+2,2);
        strncpy(yyyy,dateLog+4,4);
       
        strcat(theDate,yyyy);
        strcat(theDate,"-");
        strcat(theDate,mm);
        strcat(theDate,"-");
        strcat(theDate,dd);   //convert to yyyy-mm-dd as in mysql date format  

    return;
}

How can I alter this code so that this code will scan all files in that folder and insert it properly into table. Table structure will be something like this:
mysql> desc PostpaidProfile2;

+---------------+------------------+------+-----+---------+----------------+
| Field         | Type             | Null | Key | Default | Extra          |
+---------------+------------------+------+-----+---------+----------------+
| RecordID      | int(10) unsigned |      | PRI | NULL    | auto_increment |
| MobileNumber  | varchar(11)      | YES  |     | NULL    |                |
| Status        | tinyint(1)       | YES  |     | 0       |                |
| CreateDate    | datetime         | YES  |     | NULL    |                |
| TerminateDate | datetime         | YES  |     | NULL    |                |
| PackagePlan   | varchar(100)     | YES  |     | NULL    |                |
+---------------+------------------+------+-----+---------+----------------+

There are 2 files received every hour namely DB1-HH-DD-MM-YYYY.txt and DB2-HH-DD-MM-YYYY.txt. If this program read DB1-HH-DD-MM-YYYY.txt, then it will insert all the contents of the file to the PostpaidProfile2 table and in the PackagePlan field, it will indicate "Unlimited" and vice versa for DB2-HH-DD-MM-YYYY.txt which will insert "Pay-Per-Use" in the PackagePlan field. After reading those files, they will be removed and this program will wait for another files that will be coming in on the next hour.

Hopefully u guys can understand what I mean..:)

Hi All,

I've written a code to append string into a file. How to modify that code so that, before the string had been appended, it should check the existing of the file. If the file does exist, then it can instruct to append the string into that particular file. But if that file doesn't exist, the program should return error . I've try to modify it but failed.I cant compile that program.

Below are my code:

void writeLogFile(char line2[1600])
{
    FILE *fp;

    fp=fopen("internet_access_lookup_table.txt", "a");

    if(fp==NULL) {
        printf("file not found!\n");
        exit(0);
    }
    else {

        if ( (fputs(line2, fp)) == EOF) {
            printf("error write...");
        }
        if ( (fputs("\n", fp)) == EOF) {
            printf("error write1...");
        }
    }

    fclose(fp);
    
}

Thanks in advance

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.