Thread: reading data from file

  1. #1
    Registered User
    Join Date
    Aug 2011
    Location
    London
    Posts
    8

    Post reading data from file

    Hello All,

    I'm a complete newbie in C programming and am learning bits and pieces from online tutorials.

    I am trying to read some information from a text file, i have broken down reading this information from this file into 4 tasks.

    1) Read gain values i.e. variables with single values

    2) Read variables with a number of values or array of values

    3) Most importantly how do i get it to ignore white spaces. For e.g. see first two Vaules i.e. Value1= 5000.0 & Value2= 10.0 (placement of = )

    Moment i change it to Value1 = 5000.0 & Value2 = 10.0 i get different result.

    4) Lastly ignore anything starting with %

    Now i can do(barely) the first part (see attached c code and input_pars.txt), but i cannot figure out how to do the second and print out (as i did with the first) or third.

    I would really appreciate if someone could give me an idea or pointer as to what needs to be done or point me to a simple example.

    Apologies for really newbie questions.

    Any help is appreciated, thanks in advance.
    Attached Files Attached Files

  2. #2
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    3 - Use fscanf:
    Code:
    fscanf( fp, "%*[^=]=%f", &floatingpointnumber );
    Ignore everything that isn't an equal sign then read the equal sign, then read the number.

    4 - Use sscanf instead, and read each line with fgets, check the first value to see if it is a %, and if not, do the above.

    I haven't had my coffee yet, so you have to try it yourself, but it looks about right.


    Quzah.
    Hope is the first step on the road to disappointment.

  3. #3
    Registered User
    Join Date
    Aug 2011
    Location
    London
    Posts
    8
    Hi Thanks for your reply,

    I want to read the name ignore the space, then read the equal sign then ignore space then read number.

    Once carriage return is reached then move to next line do same till it reaches an array of values, read that move to the next line read what ever comes next. If it encounters something starting with % ignore move on etc etc...

    i'm trying out fgets to read line but not getting anywhere. I'll post my code soon.....

    Any help is appreciated.

  4. #4
    Registered User
    Join Date
    Aug 2011
    Location
    London
    Posts
    8

    Post

    Hello all,

    Quzah, thanks for your suggestions.I kinda got bits and pieces of it but did not follow as i honestly did not understand it. As mentioned i'm a complete newbie thrown in the deep end and my learning curve is goint to be very steep. Therefore i need examples.....thanks anyways suggestion are very helpful, they give starting points....and yes your suggestion helped

    OK Now i'm really stuck,

    I have modified the code to read name then equal sign then number :

    Code:
    /*#include <iostream>*/
    #include <stdlib.h>
    #include <stdio.h>
    #include<math.h>
    #define SIZE 80
    
    FILE*fp;
    
    char var[SIZE],var1[SIZE];
    static double Gain1,Gain2,Gain3,Gain4,Gain5,Gain6,Gain7;
    
    
    int main ()
    {
      if((fp=fopen("input_pars.txt","r"))==NULL){
          printf("******* Cannot open file *********** \n");
    	  exit(EXIT_FAILURE);
       }
        else{
            printf("~~File Read~~ \n");
        }
    
      fscanf( fp, "%s %s %lf",var,var1,&Gain1 );
        printf("%s %s %.2f\n",var,var1,Gain1);
    
      fscanf (fp, "%s %s %lf",var,var1,&Gain2);
        printf("%s %s %.2f\n", var,var1,Gain2);
    
      fscanf (fp, "%s %s %lf",var,var1,&Gain3);
        printf("%s %s %.2f\n", var,var1,Gain3);
    
      fscanf (fp, "%s %s %lf",var,var1,&Gain4);
        printf("%s %s %.2f\n", var,var1,Gain4);
    
      fscanf (fp, "%s %s %lf",var,var1,&Gain5);
        printf("%s %s %.2f\n", var,var1,Gain5);
    
      fscanf (fp, "%s %s %lf",var,var1,&Gain6);
        printf("%s %s %.2f\n", var,var1,Gain6);
    
      fscanf (fp, "%s %s %lf",var,var1,&Gain7);
        printf("%s %s %.2f\n", var,var1,Gain7);
      fclose (fp);
      return 0;
    }
    However i cannot figure out how to recognize a %. In the above code it reads everything

    i tried the following:

    Code:
    /*#include <iostream>*/
    #include <stdlib.h>
    #include <stdio.h>
    #include<math.h>
    #define SIZE 80
    
    FILE*fp;
    
    char var[SIZE],var1[SIZE];
    static double Gain1,Gain2,Gain3,Gain4,Gain5,Gain6,Gain7;
    int com;
    int n = 0;
    
    int main ()
    {
      if((fp=fopen("input_pars.txt","r"))==NULL){
          printf("******* Cannot open file *********** \n");
    	  exit(EXIT_FAILURE);
       }
        else{
            printf("~~File Read~~ \n");
        }
        
        do {
          com = getc (fp);
          if (com == '%') n++;
        } while (com != EOF);
        printf ("Number of Percentage signs %d =.\n",n);    // 
    
      fclose (fp);
    
      return 0;
    In the above i can get it to count "%" (learnt from another example) but dont know how to get it to ignore anything starting with "%". I'm stuck......and move to next line

  5. #5
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    Read the documentation for scanf very carefully. Any whitespace in the format string will match any number of whitespace characters:
    Code:
    fscanf(fp, "%s = %f", var, &Gain1);
    The docs also tell you how to match a literal percent character:
    Quote Originally Posted by man scanf
    The following conversion specifiers are available:


    % Matches a literal '%'. That is, %% in the format string matches a single input '%' character. No conversion is done (but initial white space characters are dis-
    carded), and assignment does not occur.

  6. #6
    Registered User
    Join Date
    Aug 2011
    Location
    London
    Posts
    8
    So is my code incorrect? or do you think i need to code it differently?

    Please advice.

  7. #7
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    Yes, your code is incorrect. It matches the format you want, but also matches a bunch of other, invalid formats. C can't read your mind or your intentions, so you must always specify exactly what you want.

    You did:
    Code:
    fscanf(fp, "%s %s %lf", var, var1, &Gain1);
    That second %s in there matches any non-whitespace characters. That could be a single '=', or it could be "ThisIsNotAValidInputFile". On the other hand, if you do:
    Code:
    fscanf(fp, "%s = %lf", var, &Gain1);
    You will match the field name, any number of white space characters, exactly one equals sign, any number of whitespace characters, then a float. That is exactly the format you want to match, so that is exactly what you need to tell fscanf to look for.

    If you want to ignore lines starting with a '%' (I'm assuming they're comments), then you need to read your lines in with fgets, and parse them with sscanf. Something like:
    Code:
    while (fgets(buf, SIZE, fp) != NULL)
        if buf[0] == '%'
            ignore it
        else
            sscanf(buf, ...)

  8. #8
    Registered User
    Join Date
    Aug 2011
    Location
    London
    Posts
    8

    Post

    Hi anduril462,

    Thanks for your reply, i need such advice and guidance . I'll work on your suggestions and reply back.

    one question:

    using fscanf can i read in something like A = 1 2 3 4 5 from a text file?


    thanks

  9. #9
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    Quote Originally Posted by kermos View Post
    using fscanf can i read in something like A = 1 2 3 4 5 from a text file?
    Yes.

  10. #10
    Registered User
    Join Date
    Aug 2011
    Location
    London
    Posts
    8
    Gents,

    I've made some changes and simplified the input file i want to read.

    I've also simplified the code which will read the input data:

    Code:
    include <stdlib.h>
    #include <stdio.h>
    #include<math.h>
    #define SIZE 80
    
    FILE*fp;
    
    char var[SIZE],var1[SIZE];
    static double Gain1,Gain2,Gain3,Gain4,Gain5,Gain6,Gain7;
    int c;
    int n = 0;
    
    int main ()
    {
      if((fp=fopen("input_pars.txt","r"))==NULL){
          printf("******* Cannot open file *********** \n");
    	  exit(EXIT_FAILURE);
       }
        else{
            printf("~~File Read~~ \n");
        }
    
      fscanf( fp, "%s %lf",var,&Gain1 );
        printf("%s %.2f\n",var,Gain1);
    
      fscanf (fp, "%s %lf",var,&Gain2);
        printf("%s %.2f\n", var,Gain2);
    
      fscanf (fp, "%s %lf",var,&Gain3);
        printf("%s %.2f\n", var,Gain3);
    
      fscanf (fp, "%s %lf",var,&Gain4);
        printf("%s %.2f\n", var,Gain4);
    
      fscanf (fp, "%s %lf",var,&Gain5);
        printf("%s %.2f\n", var,Gain5);
    
      fscanf (fp, "%s %lf",var,&Gain6);
        printf("%s %.2f\n", var,Gain6);
    
      fscanf (fp, "%s %lf",var,&Gain7);
        printf("%s %.2f\n", var,Gain7);
    
      fclose (fp);
      return 0;
    }
    The above code reads the file half way and stops, can some please highlight whats happening.

    Please note the attached input_par.txt is a cut down/test verison. There are more and i'm just working with these as i'm assuming if these work then rest of them will also work.

    Please help.


    Sorry Cannot seem to attach input_pars.txt, so included the data in here.

    Code:
    Value1= 5000.0 
    Value2= 10.0
    
    
    
    Array1= -0.5 -0.0982 0 0.0982 0.5
    Array2= 16000 6000 0 -6000 -16000
    Array3= 0 0.25 0.5 0.75 1 1.25 1.5 1.75 2 2.5 3 3.5 4 4.5 5
    
    
    Value3= 1
    Value4= 60
    Value5= 1
    Value6= 0.15

  11. #11
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    It would be nice if you posted actual output.

    I would guess that it's because you only request 7 string-double pairs, but there are way more. And your format strings will not match the Array parts, so you will get unexpected results there.

    You need to specify exactly what you want. scanf can't read your mind and doesn't know your intentions. If you want to read an array with 5 doubles, you need 5 %lf format specifiers and 5 vars to hold them, all with only one %s at the beginning of the line.

    You should check the return value of every fscanf call to make sure it worked properly.

    Seriously, read the scanf docs carefully and Google for examples and tutorials.

  12. #12
    Registered User
    Join Date
    Aug 2011
    Location
    London
    Posts
    8
    Hi, i tried adding the a screen shot of the output but the could not do that through i'll attempt to add it again or i'll just paste it in here.

  13. #13
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Quote Originally Posted by kermos View Post
    Hi, i tried adding the a screen shot of the output but the could not do that through i'll attempt to add it again or i'll just paste it in here.
    You're probably running into problems because you don't have enough posts yet... I think you need 20 or 25 before you can edit your profile, attach stuff or upload images...

  14. #14
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    Quote Originally Posted by kermos View Post
    Hi, i tried adding the a screen shot of the output but the could not do that through i'll attempt to add it again or i'll just paste it in here.
    Just copy-paste it into a post here.

  15. #15
    Registered User
    Join Date
    Aug 2011
    Location
    London
    Posts
    8

    Post

    Hi anduril462,

    I've posted the out put here,

    Code:
    ~~File Read~~
    Value1= 5000.00
    Value2= 10.00
    Array1= -0.50
    -0.0982 0.00
    0.0982 0.50
    Array2= 16000.00
    6000 0.00
    
    Process returned 0 (0x0)   execution time : 0.031 s
    Press any key to continue.
    Input is "input_par.txt", see below:

    Code:
    Value1= 5000.0 
    Value2= 10.0
    
    
    
    Array1= -0.5 -0.0982 0 0.0982 0.5
    Array2= 16000 6000 0 -6000 -16000
    Array3= 0 0.25 0.5 0.75 1 1.25 1.5 1.75 2 2.5 3 3.5 4 4.5 5
    
    
    Value3= 1
    Value4= 60
    Value5= 1
    Value6= 0.15

    If you dont mind, i have given this a short with fgets & sscanf and had mixed success. If you guys dont mind can i post that code & output too.

    I really really really appreciate the help,

    ps i've been doing c programme for literally last 10 days.

    Thanks.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 13
    Last Post: 05-31-2009, 11:30 AM
  2. Reading from a file and using the data
    By Ste_Mulv in forum C Programming
    Replies: 3
    Last Post: 04-01-2009, 07:44 AM
  3. Reading data from file
    By mvm2008 in forum C Programming
    Replies: 3
    Last Post: 07-23-2008, 10:56 AM
  4. reading data from a file
    By s_siouris in forum C Programming
    Replies: 12
    Last Post: 03-12-2008, 05:31 PM
  5. Replies: 2
    Last Post: 06-16-2005, 10:03 AM