Reading program parameters from a file

This is a discussion on Reading program parameters from a file within the C Programming forums, part of the General Programming Boards category; I've been wanting to know how to do this for years. I have a text file called run1.txt that contains ...

  1. #1
    Registered User
    Join Date
    Nov 2003
    Posts
    46

    Reading program parameters from a file

    I've been wanting to know how to do this for years. I have a text file called run1.txt that contains parameter names and values that I'd like to read and store into variables. I have coded all the parts I know how but I don't know how to deal with the part labeled pseudo code.

    Also run1.txt is in the same folder as the executable but it still cannot be found. What should parameterfile[] equal? Apparently "run1.txt" isn't enough.

    Thanks,
    Peter

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    #define MAXWORDLENGTH 50
    
    double getparamfromfile(char parameterfile[],char parametername[]){
        FILE *fp;
        double param;
        char firstword[MAXWORDLENGTH], secondword[MAXWORDLENGTH];
        
     	fp=fopen(parameterfile, "r");
     	if(fp==NULL){
            /**********this is happening because "run1.txt" apparently isn't a findable file*******/
     		printf("cannot open parameterfile called %s\n", parameterfile); 
     		abort();
     	}
    
     	/*pseudo code starts here*/
     	
                 while (not End of File){
     	 	if ( strcmp(first word in line, parametername) ){
     	   	    read secondword
     	   	    param = atof(secondword);
     	   	    return param;
     	 	} 
                    index to the next line
                 } /*while*/
        
     	/*pseudo code ends here*/
     	
     	printf("can't find parameter %s in file %s\n",parametername, parameterfile);
     	system("PAUSE");
        abort();
     	
    } /*getparamfrom file*/
    
    
    int main(void){
       double criticalbias;
        
       criticalbias = getparamfromfile("run1.txt","CriticalBias");
      
       printf("criticalbias = %f\n",criticalbias);
      
       system("PAUSE");	
       return 0;
    }
    run1.txt

    this file contains parameters to be used during run1


    MaximumNumberOfGenerations 100 the remainder of the text in this line should be ignored

    CriticalBias 0.87 the remainder of the text in this line should be ignored
    PopulationSize 20

    SurvivalFraction .80

    more parameters can be inserted here
    Last edited by petermichaux; 12-01-2003 at 06:21 PM.

  2. #2
    Registered User linuxdude's Avatar
    Join Date
    Mar 2003
    Location
    Louisiana
    Posts
    926
    Code:
    fp=fopen("run1.txt","r");
    unless parameterfile is defined earlier as run1.txt
    for your while loope
    Code:
    while(ch=getchar()!=EOF && ch!=' '){

  3. #3
    End Of Line Hammer's Avatar
    Join Date
    Apr 2002
    Posts
    6,231
    >>while(ch=getchar()!=EOF && ch!=' ')
    Spot the deliberate mistake?

    Read a line in memory, and parse it there. Use fgets() for the first part, then whatever parsing routine you like (maybe making you're own will allow you more control).
    When all else fails, read the instructions.
    If you're posting code, use code tags: [code] /* insert code here */ [/code]

  4. #4
    Registered User
    Join Date
    Nov 2003
    Posts
    46
    my file was accidently named run1.txt.txt. oops!
    Last edited by petermichaux; 12-01-2003 at 08:39 PM.

  5. #5
    Been here, done that.
    Join Date
    May 2003
    Posts
    1,161

    Re: Reading program parameters from a file

    Originally posted by petermichaux my file was accidently named run1.txt.txt. oops!
    [/B]
    Use a real file manger -- like ZTree! It doesn't hide the file extensions.

    Code:
    /*pseudo code starts here*/
    // Use fgets() to read a line into buffer and compare to EOF
    while (not End of File) 
    {
        if ( strcmp(first word in line, parametername) )
        // strcmp(buffer, parametername) == 0)
        {
            // secondword starts after buffer[strlen(parametername)]
             read secondword
             param = atof(secondword);
             return param;
         } 
         index to the next line    // Done automatically in while statement
    } /*while*/
        
    /*pseudo code ends here*/

    Code:
    system("PAUSE");
    I'm still waiting for an explanation as to why this command, which is not portable and high in resources by calling the operating system, is better than a call to a simple and standard C function like:
    Code:
    getchar();  :confused:
    Definition: Politics -- Latin, from
    poly meaning many and
    tics meaning blood sucking parasites
    -- Tom Smothers

  6. #6
    Registered User
    Join Date
    Nov 2003
    Posts
    46
    I'm willing to bet there is a very slick solution to parsing the fairly predictible file I'm reading. So far I've only come up with bulky brute force methods that seem like overkill. I have to use a lot of flags and check every character for many cases. Any suggestions or links that might help? (i've never parsed anything before)

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    #define MAXWORDLENGTH 100
    #define MAXLINELENGTH 500
    
    double getparamfromfile(char parameterfile[],char parametername[]){
        FILE *fp;
        double param;
        char firstword[MAXWORDLENGTH], secondword[MAXWORDLENGTH];
        char line [MAXLINELENGTH];
        char*fgetsreturn;
        int i,j;
        int firststart, firstend, secondstart,secondend;
        
     	fp=fopen(parameterfile, "r");
     	if(fp==NULL){
            printf("cannot open parameterfile called %s\n", parameterfile); 
     		system("PAUSE");
            abort();
     	}
     	
     	while ((fgets(line, MAXLINELENGTH, fp))!=NULL){
     	     printf("%s",line);
                         
                         There must be a slick way to do the following
    
                         determine if there are two words in the line and what they are
                         if the first word matches parametername{
                              param = atof(the second word)
                         
                              return param;
                        }
    
     	} /*while*/
        
        
     	printf("fgets has returned NULL in getparamfromfile\n");
     	printf("this probably means that %s could not be found in %s\n",parametername, parameterfile);
     	system("PAUSE");
     	abort();
    	
    } /*getparamfrom file*/
    
    
    int main(void){
       double criticalbias;
        
       criticalbias = getparamfromfile("run1.txt","CriticalBias");
      
       printf("criticalbias = %f\n",criticalbias);
      
       system("PAUSE");	
       return 0;
    }
    
    //run1.txt
    //
    //this file contains parameters to be used during run1
    //
    //
    //MaximumNumberOfGenerations 100 the remainder of the text in this line should be ignored
    //
    //CriticalBias 0.87 the remainder of the text in this line should be ignored
    //PopulationSize 20
    //
    //SurvivalFraction .80
    //
    Last edited by petermichaux; 12-01-2003 at 11:31 PM.

  7. #7
    Been here, done that.
    Join Date
    May 2003
    Posts
    1,161
    You really need to give us more than "parsing the fairly predictible file". Predictable in what way? What does the file actually look like? What different formats can each line take? Do you know what the "second words" will be or are they completely arbitrary?

    Based on the example, all lines start with // -- why?
    Second thing on the line can be a word -- do you know ALL the words possible?
    Third thing is a number, either with or without a decimal
    Rest of the line can be ignored.

    The // should only start lines that don't have valid data -- i.e. comments. Valid lines should start with the parameter.
    Definition: Politics -- Latin, from
    poly meaning many and
    tics meaning blood sucking parasites
    -- Tom Smothers

  8. #8
    End Of Line Hammer's Avatar
    Join Date
    Apr 2002
    Posts
    6,231
    One example:

    Code:
    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    
    int main(void)
    {
      char line[] = "Height=1";  /* Simulated input */
      char *p;
      int i;
      
      p = strchr(line, '=');
      if (p)
      {
        /* p now points to equals sign */
        *p = '\0';
        p++;
        printf ("The parameter name is:  %s\n", line);
        if (*p != '\0')
        {
          i = strtol (p, NULL, 10);  /* Do some validation if you want */
          printf ("The parameter value is: %d\n", i);
        }
      }
      
      return(0);
    }
    
    /*  My output:
    
    The parameter name is:  Height
    The parameter value is: 1
    
    */
    When all else fails, read the instructions.
    If you're posting code, use code tags: [code] /* insert code here */ [/code]

  9. #9
    Registered User
    Join Date
    Nov 2003
    Posts
    46
    Hammer,

    Thanks for the reply. I like the way you changed the = to a '\0'. I'm going to use that trick!

    I added a couple of lines of code to check the status of errno when the parameter value isn't convertable to a long. I'm surprised that strtol isn't changing the value of errno to ERANGE. I think at the end of the program the value of errno should be 34 on my computer by reading the definition of ERANGE in errno.h

    #define ERANGE 34


    -Peter
    Code:
    #include <stdio.h>
    #include <string.h>
    #include <errno.h>
    #include <stdlib.h>
    
    int main(void){
      char line[] = "Height=r1 ";  /* Simulated input */
      char *p;
      int i;
      
      errno=-5;  
      
      p = strchr(line, '=');
      if (p)
      {
        /* p now points to equals sign */
        *p = '\0';
        p++;
        printf ("The parameter name is:  %s\n", line);
        if (*p != '\0')
        {
          i = strtol (p, NULL, 10);  /* Do some validation if you want */
          printf("errno = %d\n",errno);
          printf ("The parameter value is: %d\n", i);
        }
      }
      
      system("PAUSE");
      return(0);
    }

    The ouput is

    The parameter name is: Height
    errno = -5
    The parameter value is: 0
    Press any key to continue . . .
    Last edited by petermichaux; 12-02-2003 at 09:21 PM.

  10. #10
    End Of Line Hammer's Avatar
    Join Date
    Apr 2002
    Posts
    6,231
    Adapt this
    Code:
    #include <stdio.h>
    #include <limits.h>
    #include <stdlib.h>
    
    int main(void)
    {
      char  buf[] = "11";
      char  *p;
      int   i;
      long  l;
    
      l = strtol(buf, &p, 10);
    
      if (l < INT_MIN || INT_MAX < l || *p != '\0')
      {
        printf("error\n");
      }
      else
      {
        i = l;
        printf("Number %d\n", i);
      }
    
      return(0);
    }
    When all else fails, read the instructions.
    If you're posting code, use code tags: [code] /* insert code here */ [/code]

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. opening empty file causes access violation
    By trevordunstan in forum C Programming
    Replies: 10
    Last Post: 10-22-2008, 12:19 AM
  2. sequential file program
    By needhelpbad in forum C Programming
    Replies: 80
    Last Post: 06-08-2008, 02:04 PM
  3. help with text input
    By Alphawaves in forum C Programming
    Replies: 8
    Last Post: 04-08-2007, 05:54 PM
  4. reading parameters from a file
    By jags007 in forum C Programming
    Replies: 3
    Last Post: 05-22-2006, 01:39 PM
  5. Need a suggestion on a school project..
    By Screwz Luse in forum C Programming
    Replies: 5
    Last Post: 11-27-2001, 02:58 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21