0

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;
}
2
Contributors
2
Replies
4
Views
6 Years
Discussion Span
Last Post by iwanttolearnc
1

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
}
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.