help with reading a data file

This is a discussion on help with reading a data file within the C Programming forums, part of the General Programming Boards category; Im a c programming rookie, and i could use some help with writing a data file, reading that file, and ...

  1. #1
    Registered User
    Join Date
    Dec 2001
    Posts
    16

    help with reading a data file

    Im a c programming rookie, and i could use some help with writing a data file, reading that file, and manipulating that data.

    I guess the best way to help explain this is to make up a simple sample problem.

    Lets say your a water billing company with three customers, you charge 10cents per gallon of water if the customer uses 100 gallons or less and 20cents per gallon if the customer goes over 100 gallons.
    Customer Numbers-----Gallons Consumed
    10--------------------------500
    268------------------------20
    780------------------------800

    First off how would i write this into a datafile (i guess a text file) so i can build a cprogram and read this information?
    Like this?
    ID1
    customer_number 10
    gallons_consumed 500
    EndID

    ID1
    customer_number 268
    gallons_consumed 20
    EndID

    ID1
    customer_number 780
    gallons_consumed 800
    EndID
    (i save the following information as datafile.txt - im guessing the above is completely incorrect, so i could use assistance on writing a datafile, please)

    Next im wondering if this is the correct way to open/read the datafile within my c program:
    Code:
    #include <stdio.h> 
    #include <ctype.h> 
    
    int main()
    {
    	int customernumber, gallons_consumed, amountdue;
    	FILE *ifp; 
    
    	ifp = fopen("datafile", "r"); /* opens file for reading */
    }
    I dont know how to read or output the inputs from the datafile, the only thing else i think i need is a loop to calculate the cost, but i dont know how i would do this per each customer - something like this?:
    if (gallons_consumed <= 100)
    printf gallons_consumed * .10
    else
    printf gallons_consumed * .20

    Then i want to manipulate and output this data into a chart like this:
    Customer Number Gallons Consumed Amount Due
    10 500 $100.00
    268 20 $2.00
    70 800 $160.00

    Total Customers: 3
    Total Gallons Consumed: 1320
    Total Amount Due: $262.00

    How would i do this, by using a datafile? Since im a rookie, im just used to using scanf - this datafile thing is completely missing with my mind! Any tips, code, or links would be greatly appreciated! Thanks for your time...

  2. #2
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    First off how would i write this into a datafile (i guess a text file) so i can build a cprogram and read this information?
    Like this?
    ID1
    customer_number 10
    gallons_consumed 500
    EndID

    |----- snip -----|
    (i save the following information as datafile.txt - im guessing the above is completely incorrect, so i could use assistance on writing a datafile, please)
    The above would work splendidly. You need to do the following:

    1) Read the ID number line, this denotes the start of a 'record'.
    2) Read the customer_number line.
    3) Read the gallons_consumed line.
    4) Read the EndID line.

    Personally, I've used a similar method before for a not entirely different tastk. I prefer something like this:

    Code:
    /*
        Add your own error checking. I am
        assuming that the file pointer has
        been opened correctly for the sake
        of the example, and I'm assuming
        you want the record returned in a
        structure of some kind.
    */
    struct myRecord * myFun( FILE * fp )
    {
        char buf[BUFSIZ]={0};
        struct myRecord * recNew = NULL;
        int done = 0;
    
        while( fgets( buf, BUFSIZ, fp ) != NULL && !done )
        {
            switch( buf[0] )
            { 
                case 'I':
                    if( !strncmp( buf, "ID1", 3 ) )
                    {
                        if( recNew == NULL )
                            recNew = malloc( sizeof( struct myRecord ) );
                        else
                            /*error, do somehting*/
                    }
                break;
                case 'c':
                    if( !strncmp( buf, "customer_number", 15 ) )
                    {
                        /*
                            pull the number from
                            the end of the string
                            and stick it in the node
                        */
                    }
                break;
                case 'g':
                    if( !strncmp( buf, "gallons_consumed", 16 ) )
                    {
                        /*
                            pull the number from
                            the end of the string
                            and stick it in the node
                        */                }
                break;
                case 'E':
                    if( !strcmp( buf, "EndID" ) )
                    {
                        done = 1;
                    }
                break;
                default:
                    /* You have invalid data. */
            }
        }
        return recNew;
    }
    A lengthy example. I kept it as short as I could. You may see some functions you are unfamiliar with, so just go here to read up on them. Not all the functions at this link are ANSI, but they'll tell you if they aren't.

    Now on to part two:

    Next im wondering if this is the correct way to open/read the datafile within my c program:
    Yes. You've opened the file correctly. You can use 'fgets' like I did in the above example to read a line from a text file. See the provided link in the event you aren't sure how it works.

    I used a structure to contain the data. I find this best in this situation. However, if you're just tallying them up, you may want to just use sscanf once you have read a line to read the buffer and pull the chunk out that you need. If you do this, you won't need a seperate function to read the data.

    The reason I use the format I have above is because it will safely read a file until it hits the end of it, or until it encounters the end of a record. It also allows for you to discard unwanted lines. You could add a bit more to it and make it ensure safe handling or logging of duplicate lines. IE:

    ID1
    customer_record x
    customer_record y
    gallons_consumed z
    EndID

    I actually prefer binary files because you can read and write entire records in one shot and have the data go directly into your structures. However, if you need to use text so you can manually edit it, the above solution should suffice.

    [edit]
    As I was typing this novel, Salem beat me to it...
    [/edit]


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

  3. #3
    Registered User
    Join Date
    Dec 2001
    Posts
    16
    Thanks for the tips! I appreciate it! Some of it was alittle too far advanced for me, but i was able achieve some progress im almost finished i think.

    I changed my datafile, hopefully to simplify the procedure - i only put two columns of numbers. Column #1 = customer_number and Column #2 = gallons_used.

    Example datafile.txt:
    10 50
    22 20
    70 800
    100 400
    250 60

    I used your advise and went with fgets() & sscanf(). I also put in a counter which allowed me to print out the total number of customers.

    Code:
    #include <stdio.h>
    #include <string.h>
    
    int main()
    {
       int customer_number, gallons_used, amount_due;
       int CustomerCount = 0;
       char str[255];
       FILE *fpr = fopen("datafile.txt", "rt");
       
       if( fpr == NULL )
           return 1;
       
       printf("Customer Number\t\tWater Usage\t\tAmount Due\n");
       while( feof( fpr ) == 0 )
       {
           fgets(str, sizeof(str), fpr);	
           if(sscanf( str, "%d %d", &customer_number, &gallons_used) != 2)
               break;
           CustomerCount++;	
           printf("%d\t\t\t%d\n", customer_number, gallons_used);	
       }
       fclose(fpr);
       printf("\nThere are %d customers.\n", CustomerCount);
    
       return 0;
    }
    and that produces an output of:
    Code:
    Customer Number         Water Usage             Amount Due
    10                                  50
    22                                  20
    70                                  800
    100                                400
    250                                60
    
    There are 5 customers.
    Now i only need to accomplish three more objectives.
    #1) How do i add the numbers in column two, so that i can figure out the total amount of consumed water.
    #2) How do i take the data from column two and multiply it by a set price? So i can find the Amount Due for each costomer. For example lets say i now charged:
    Water consumed 000 to 100 gallons = $0.10 per each gallon.
    Water consumed 101 to 200 gallons = $0.20 per each gallon.
    Water consumed 201 to 999 gallons = $0.30 per each gallon.
    I know i would need a simple loop kinda like this:
    if (gallons_used >= 999)
    charge = .30
    else if (gallons_used >= 200)
    charge = .20
    else (gallons_used >= 100)
    charge = .10
    But I dont know how to point towards column twos gallons used information. And i dont where or how i would put this code.
    #3) Once i figure out each customers amount due, i need to find the total amount due from all the customers - in other words find a way to add up all everything in column 3 (amount due). Basically repeating objective number 1.

    Also do i need to change the datafile.txt back to where i had it before or will the simplied version work fine too? Thanks for any help!!
    Last edited by zipfur; 11-02-2002 at 05:11 PM.

  4. #4
    Registered User
    Join Date
    Dec 2001
    Posts
    16
    Originally posted by Salem
    So what's stopping you?
    I dont know, I wish I knew!
    Writing the pseudo code helps me out alot. I was up til 5am just playing with that small amount of code i had above and reading tutorials - never got tired of it! Im slow at this, but i enjoy and have a good time doing it. I think im good at the step by step problem solving part, i know what needs to be done, but when it comes to writing down the code i lack the experience & know how. Maybe one day...

  5. #5
    Registered User
    Join Date
    Dec 2001
    Posts
    16
    thanks! after looking at it, it seams pretty easy...

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Data Structure Eror
    By prominababy in forum C Programming
    Replies: 3
    Last Post: 01-06-2009, 09:35 AM
  2. gcc link external library
    By spank in forum C Programming
    Replies: 6
    Last Post: 08-08-2007, 04:44 PM
  3. reading data from a file
    By brianptodd in forum C++ Programming
    Replies: 1
    Last Post: 11-07-2003, 06:50 PM
  4. simulate Grep command in Unix using C
    By laxmi in forum C Programming
    Replies: 6
    Last Post: 05-10-2002, 05:10 PM
  5. what does this mean to you?
    By pkananen in forum C++ Programming
    Replies: 8
    Last Post: 02-04-2002, 03:58 PM

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