read file in C

Tom3333
Tom3333 used Ask the Experts™
on
I created a code in C for read a file. The code is working properly except the the last line of the file.
The problem is that for the file :

A1 20 B1
B2 10 C1  

my code is read :
A1
20
B1

B2
10
C1

B2


How to fix this???
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®

Author

Commented:
I forgot to present my code. My code is:


#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAX2 100
#define DELIMITER " \t,"

int main(void)
{
      FILE *fp;
        char data[MAX2];
      char *data1;
      char *data2;
      char *data3;
fp=fopen("a.txt","r");

      if (fp==NULL)
            {
                  printf("Cannot open the file");
                  exit(1);
            }
            else
            {
            while(!feof(fp))
                  {
                  fgets(data,MAX2,fp);
                  data1=strtok(data,DELIMITER);
                  //printf("HELLO:%s\n",data1);
                        while ((data2=strtok (NULL,DELIMITER))!= NULL)
                              {
                              //printf("DDD:%s\n",data2);                                    
                              data3=strtok (NULL,DELIMITER);
                              //printf("SS:%s\n",data3);                                    
                              }

                  }
            }
      
fclose(fp);
return 0;
}
Your problem is the feof condition is set by the read...

You need to restructure as follows:

 else
            {
            fgets(data,MAX2,fp);
            while(!feof(fp))
                  {
                  data1=strtok(data,DELIMITER);
                  while ((data2=strtok (NULL,DELIMITER))!= NULL)
                              {
                              data3=strtok (NULL,DELIMITER);
                              }
                  fgets(data,MAX2,fp);
                  }
            }

Open in new window

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial