Thread: Getting variables and numbers from a text file.

  1. #1
    Registered User
    Join Date
    Jul 2010
    Location
    Liverpool
    Posts
    34

    Question Getting variables and numbers from a text file.

    I'm a beginner at C programming but have been tasked with the following:

    I have a text file with data in it in the form

    variablename:float:units

    i.e. colon delimited values.

    I need to take the variablename and have it equate to the float number in the middle column. My code at the moment will display the lines of the text file and attempts to deposit characters up to the colon character into a text file 'deposit.c' but I'm not sure how to extract the variable name and the float number and equate them.

    My code so far is:

    Code:
    /* Prints all lines of a file data.txt out with line number */
    
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    
    main ()
    
    {
      FILE *fs,*ft;
     int i,j;
     char arra[128][128];
     char line[128];  /* max. line size */
     char filename;
     char return_val;
     char ch;
    
     printf("Type in the name and extension of the model file e.g. data.txt\n");
     scanf("%s",&filename);
    
     printf("Filename is %s\n",&filename);
    
     fs=fopen(&filename,"r");  /* Opens file for reading text */
     ft=fopen("deposit.c","w");
    
     for (i=0; i<128; i++)
     for (j=0; j<128; j++)
     arra[i][j]= '\0';
    
     for (i=0; i<128; i++)
      line[i] = '\0';
    
     if (fs !=NULL)  /* ! = 'not' */
    
     {
     i=0;
     while (fgets (line,sizeof line,fs) !=NULL) /* read a line */
    
     {
     strcpy(arra[i], line);  /* Puts line into into same number array */
     printf("Line Number %d: %s", i+1,&arra[i]);
     i++;
     }
    
     /* Put extra formatting in here */
     /* Need to create variable from first column and have it defining the number in the second column */
    
     while(1)
       {
         ch = fgetc(fs);
         if (ch == ':')
           break;
         else
           fputc (ch, ft);  /* puts letters up to colon into file ft */
    
       }
    
     fclose(fs);
     fclose(ft);
     }
    
     else
    
      { printf("Could not open file\n");
          }
    
     return 0;
    
     }
    I realise this code is probably not the most efficient way of displaying the lines but that is an intermediate step and the lines will not need to be displayed in the final code.

    My data.txt file is

    Code:
    Aldensity:2700:kg/m3
    spar:4:0
    rib:8:0
    Obviously I could do it manually but the actual file I'll be using is up to 3000 lines.. and my project supervisor wants a program to do it!

    Thank you very much for any help.

  2. #2
    Registered User claudiu's Avatar
    Join Date
    Feb 2010
    Location
    London, United Kingdom
    Posts
    2,094
    If by equating you mean you need to create a variable in the C program with the exact name and with the value you read from the file that is pretty much impossible as far as I know since there is no code reflection in C. (i.e. you cannot modify your code based on what you read from a file).
    1. Get rid of gets(). Never ever ever use it again. Replace it with fgets() and use that instead.
    2. Get rid of void main and replace it with int main(void) and return 0 at the end of the function.
    3. Get rid of conio.h and other antiquated DOS crap headers.
    4. Don't cast the return value of malloc, even if you always always always make sure that stdlib.h is included.

  3. #3
    Registered User
    Join Date
    Jul 2010
    Location
    Liverpool
    Posts
    34
    Yep that's what I meant. Oh dear.

    The program is supposed to estimate the weight of an aircraft based on the sum of all its parts and should be able to select between different models e.g. the two-seat and the four-seat version. Sounds like I might have to do it manually after all, do you have any suggestions for how this could be done?

    Thanks

  4. #4
    Registered User claudiu's Avatar
    Join Date
    Feb 2010
    Location
    London, United Kingdom
    Posts
    2,094
    Well, if you are familiar with Java you might have better luck there, depending on your actual performance specifications. Here is an article on how to use some basic Java Reflection. As far as I know, neither C/C++ support reflection, but Java does, and it's pretty simple to use.

    Here is the link:

    Using Java Reflection

    Best of luck to you!
    1. Get rid of gets(). Never ever ever use it again. Replace it with fgets() and use that instead.
    2. Get rid of void main and replace it with int main(void) and return 0 at the end of the function.
    3. Get rid of conio.h and other antiquated DOS crap headers.
    4. Don't cast the return value of malloc, even if you always always always make sure that stdlib.h is included.

  5. #5
    Registered User claudiu's Avatar
    Join Date
    Feb 2010
    Location
    London, United Kingdom
    Posts
    2,094
    If you want to do it in C I would recommend using .ini files or a similar properties representation. It just doesn't seem feasable to hard code 3000 different parameters, especially if new ones can be added later or present ones removed.
    1. Get rid of gets(). Never ever ever use it again. Replace it with fgets() and use that instead.
    2. Get rid of void main and replace it with int main(void) and return 0 at the end of the function.
    3. Get rid of conio.h and other antiquated DOS crap headers.
    4. Don't cast the return value of malloc, even if you always always always make sure that stdlib.h is included.

  6. #6
    Registered User
    Join Date
    Jun 2010
    Posts
    45
    wouldnt a scripting language be better?
    Last edited by LordPc; 07-06-2010 at 03:40 AM.

  7. #7
    Registered User
    Join Date
    Jul 2010
    Location
    Liverpool
    Posts
    34
    Thanks, I have zero experience in Java but I'll have a look at it. I have a lot of Matlab experience and wish I could use that but my supervisor this year says it's too slow, which is fair enough I guess.

    I've found this code here: Reading a file to variables

    which looks like a similar problem but the solution uses C++. Would it be worth learning C++ instead of C?

    EDIT: Also, in that problem the variables are known, a,b,c,d. It looks like that's what I need to do?

    Thank you all for your help and sorry if I'm being slow.

  8. #8
    Registered User
    Join Date
    May 2010
    Location
    Naypyidaw
    Posts
    1,314
    I think you use need:
    Code:
     struct VAR {
         char *name;
         float value;
    };
    The program is supposed to estimate the weight of an aircraft based on the sum of all its parts and should be able to select between different models e.g. the two-seat and the four-seat version.
    Base on your problem, i don't think you really need reflection at all.
    Last edited by Bayint Naung; 07-06-2010 at 04:52 AM.

  9. #9
    Registered User
    Join Date
    Jun 2010
    Posts
    5
    I am not sure of understanding what you want to do with the data you obtain from the file, but i agree with Bayint. I think you can manage it with an array of structs. It depends on what do you have to do

  10. #10
    Registered User
    Join Date
    Jul 2010
    Location
    Liverpool
    Posts
    34
    The part I'm having problems with is reading information from a text file in the form

    variablename1:number1:units
    variablename2:number2:units
    etc

    I want to write a C program that can read the first line up to the colon, make the variable name an actual variable, then continue reading to the second colon and grab the number. From reading some of the pages on reflection it sounds like it might be needed but I'm really not sure, does anyone have a definite answer, and maybe some help on how to do this? I'm a complete beginner at C.

    Once the variables have been read in I'll use structs, thank you for that tip.

  11. #11
    Registered User
    Join Date
    May 2010
    Location
    Naypyidaw
    Posts
    1,314
    What are you going to do with the numbers that have been read in?

    The program is supposed to estimate the weight of an aircraft based on the sum of all its parts and should be able to select between different models e.g. the two-seat and the four-seat version. Sounds like I might have to do it manually after all, do you have any suggestions for how this could be done?
    I can't relate your requirement and what you are doing.
    Give example input, output.

  12. #12
    Registered User
    Join Date
    Jul 2010
    Location
    Liverpool
    Posts
    34
    Really sorry, I didn't understand what you were asking.

    An example text file is (column headers would be variablename:number:units)

    Code:
    sparlength:4:m
    sparxsection:0.2:m2
    panellength:2:m
    panelxsection:0.03:m2
    windowlength:0.5:m
    windowxsection:0.05:m2
    enginemass:65:kg
    ...
    The C program should do the following:
    Code:
    1. Read file
    2. Get 'sparlength' and store as variable
    3.  Set 'int sparlength = 4' from the text file
    4.  Set 'float sparxsection = 0.2' similarly
    (units can be ignored completely)
    5.  Work out float sparvolume from sparlength * sparxsection
    6.  Work out float sparmass from volume * density
    etc. for the other variables
    7.  Find all variables with name 'mass' and add them up:  i.e. sparmass + panelmass + windowmass + enginemass
    I can do all of that apart from steps 3 and 4, hence the question. If it seems too complicated or reflection is required I can do it manually, it's just my supervisor would prefer it done so it works for any textfile he throws at me :S but if it's not possible, it's just not possible!

    Thank you very much for your continuing help.

  13. #13
    Registered User
    Join Date
    May 2010
    Location
    Naypyidaw
    Posts
    1,314
    Pseudo C.
    Code:
    float sparlength,sparxsector,  sparwhatever, sparmass;
    float arr[ N ];      
    
    tokens = parse(line);
    if ( match(tokens[0], "sparlength" ) 
      sparlength = atof ( tokens[1] );
    else if( match( tokens[0] , "sparxsection") ) 
       sparxsector = atof( tokens[ 1 ] ); 
    else if  ( match( tokens[0],"sparmass" ) ) {
         arr[n++] = sparmass = atof( tokens[1]) );
      }
    
    for(i = 0; i < n;i++) sum += arr[i];        // add all with name mass...
    ....

  14. #14
    Registered User
    Join Date
    Jul 2010
    Location
    Liverpool
    Posts
    34
    Thanks, that looks great and I'll definitely use it if this fails..

    Not sure I've explained myself correctly - since there's going to be about 3000 different variables and they may change I was hoping to have the program get the variable names directly from the text file.

    Would something like this work?

    Code:
    float *length,*xsector,  *whatever, *mass;   /* wildcards */
    float arr[ N ];      
    
    tokens = parse(line);
    if ( match(tokens[0], "*length" ) 
      *length = atof ( tokens[1] );
    else if( match( tokens[0] , "*xsection") ) 
       *xsector = atof( tokens[ 1 ] ); 
    else if  ( match( tokens[0],"*mass" ) ) {
         arr[n++] = *mass = atof( tokens[1]) );
      }
    But then the variables won't be declared correctly. Hmm. Oh well, I think I'll just use Bayint's solution. Thank you very much!

  15. #15
    Registered User
    Join Date
    May 2010
    Posts
    4,632
    I would use a structure to hold the 3 items per line
    Code:
    struct Items
    {
       char name[100];
       double value;
       char units[10];
    };
    As you are already reading the file a line at a time take that line an break it up using strtok() using the ':' as the
    delimiter. Now do any conversions of the character strings (ie to double) and store the values in the structure.

    The structure will have to be a dynamic array of structures because you don't know how many there will be in the file.

    After this processing you will now have an array of structures holding your values. You will now be able to do any post processing you desire as you have kept all the information.

    Jim

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Writing variables to a text doc?
    By Cielo in forum C++ Programming
    Replies: 3
    Last Post: 03-18-2008, 04:10 AM
  2. Backgammon
    By glo in forum Game Programming
    Replies: 5
    Last Post: 10-02-2006, 10:26 PM
  3. reading a text file printing line number
    By bazzano in forum C Programming
    Replies: 4
    Last Post: 09-16-2005, 10:31 AM
  4. i/o assigning variables
    By bballzone in forum C++ Programming
    Replies: 4
    Last Post: 07-30-2004, 10:49 AM
  5. Reading/Writing Files
    By r0ss in forum C Programming
    Replies: 2
    Last Post: 11-04-2003, 03:53 PM