im reading a text file that contains data in a fashion similar to this

$1.2.3.4.5.6$
%7.8.9.10.11.12%
*a.b.c.d.e*

what i want to do is read only data enclosed by '$' and skip to the next line if the data contained are not. written below is my code. im kind of stuck as to how im going this. my program closes if it reads the data enclosed by %. im guessing its a strchr problem. please help

#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <string.h>

int main ( void )
{
    
   static const char filename[] = "file.txt";
   FILE *file = fopen ( filename, "r" );
   
   if ( file != NULL )
   {
      char line [ 128 ]; /* or other suitable maximum line size */
      int num [128];
      char* parse;
      signed int x = -1;

      char* start;
      char* end;
      
      while ( fgets ( line, sizeof line, file ) != NULL ) /* read a line */
      {
            
            start = strchr(line , '$');                 
            end = strchr(start + 1 , '$');
            
            if (start != NULL && end != NULL){
                      printf ("i have read a valid data string\n");
                      }
                        
            parse = strtok (line , ".");
            while (parse != NULL){
                  x = x+1;
                  num[x] = atoi (parse);
                  printf ("atoi'd string at num[%d] is %d\n" , x , num[x]);
                  parse = strtok (NULL , ".");
            }                          
      }
      fclose ( file );
     
   }
   else
   {
      perror ( filename ); /* why didn't the file open? */
   }
   getch();
   return 0;
}

when line 25 returns NULL then line 26 is going to cause a lot of grief. You need an if statement between those two lines.

if( (start = strchr(line,'$')) != NULL)
{
   // blabla
}
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.