Link to home
Create AccountLog in
Avatar of vjabhi
vjabhi

asked on

Read Text file using c

Hi All,

I have text file in following format...

No|data1|data2
1|123|234
2|34|456

and so on...

Howto read above text file using c code. Here '|' is used as seperator.

Thanks a lot..
Abhi


ASKER CERTIFIED SOLUTION
Avatar of Kent Olsen
Kent Olsen
Flag of United States of America image

Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
See answer
Avatar of madhurdixit
madhurdixit

one more concept is that of a file pointer (FILE *myfile),
while you loop through you need to make sure you don't hit the end of file.

To check that you do

 while(!feof(myfile))
{ //do your job
}
                                                 
SOLUTION
Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
Avatar of vjabhi

ASKER

thatsks for ur feed back..
actually this is Pro* c program which reads text file and insert data to oracle.

text file format is

|1111|222|333|444|555

in my code i have to read 111 and 444
..
i am trying with folloing code... but it doesnt work..
char            s_data[100];
while(!feof(fp))
      {
            fgets(s_data,150,fp);
            //rech =strtok(s_data,"|");
            strcpy(c_msisdn,strtok(s_data,"|"));
            printf("mobile = %s\n",c_msisdn);            
            
            i= 0;
                               // TO get desired column of data (eg 444)
            while (strtok(s_data,"|")!= NULL)
            {
               // rech = strtok(NULL,"|");
                i = i + 1;
                if (i==4)
                {
                  i_mou = strtok(NULL,"|");;
                }
            }


Thanks for your help...
Abhi

Two thoughts here:

          while (strtok(s_data,"|")!= NULL)

You need to pass NULL as the string address to perform "continuation searches".  Passing s_data every time means that the search starts at the beginning of the string, and since strtok() has already replaced the first '|' with end-of-string, it will never get to the parameter you want.

char          s_data[100];
char          *position;

while(!feof(fp))
     {
          fgets(s_data,150,fp);
          //rech =strtok(s_data,"|");
          strcpy(c_msisdn,strtok(s_data,"|"));
          printf("mobile = %s\n",c_msisdn);          
           
          i= 0;
    // TO get desired column of data (eg 444)
          position = s_data;
          while (strtok(position,"|")!= NULL)
          {
             // rech = strtok(NULL,"|");
              i = i + 1;
              if (i==4)
              {
                i_mou = strtok(NULL,"|");;
              }
              position = NULL;
          }



You can also do this with sscanf().  One line, two parameters (or more as you may wish) returned.

Kent