-2

I am taking a course on C and have been faced with the following task: 1. Load XCode and start a new C project. If you wish, remove any extraneous code from the project so that you are left with only what’s necessary to run the main function in your project. 2. Prompt the user to enter two values-- the first a char value of ‘D’ or ‘C’. The second value should be a floating point value representing an amount of money. 3. As each value is entered record it to a text file that saves it in the following format: D, 250\n C, 500\n 4. Test your program and examine the text file that it creates to insure that it is in the required format. 5. Write a second program that assumes a starting balance of $1,000.00 and outputs a completed ledger and final balance for the account, adding or subtracting each entry from the text file you previously created. Entries marked as a ‘C’ should be added to the account and entries marked as a ‘D’ should be debited (subtracted).

I have already created the file and am now onto step 5, I believe i know how to obtain the first character from the file to check if it is a 'c' or 'd', but after that i am not sure how to obtain the numerical value from the same line. How do I do this? This is my code so far(I am unsure what to put in the if/else if statements):

   FILE *pFile = fopen("Users/Justin/Desktop/Ledger.txt", "r");
    float startingBalance = 1000.00;
    char action;

    if(pFile != NULL)
    {
        while(!(feof(pFile)))
        {
            fgets(action, 1, pFile);

            if(action == 'D' || action == 'd')
            {

            }
            else if(action == 'C' || action == 'c')
                {

                }
            else
                printf("IO Error: Problem with file");

        }
    }



    return 0;
}
  • 1
    `fgets(action, 1, pFile);` is wrong, did the compiler give you a warning? – Yu Hao Oct 07 '14 at 10:47
  • Check [`man strtol`](http://www.manpagez.com/man/3/strtol/), and [`man fgets`](http://www.manpagez.com/man/3/fgets/). Do *not* attempt to use `fscanf()`, for that function is rather iffy to use properly in the face of malformed input / read failures. – DevSolar Oct 07 '14 at 10:48
  • 1
    And please use the return value of `fgets` to terminate reading, do not rely on `feof`. (`fgets` returns `NULL` when the end of the file is reached.) – M Oehm Oct 07 '14 at 10:50
  • ..and [man fgetc](http://linux.die.net/man/3/fgetc) – soerium Oct 07 '14 at 10:51
  • IOW, don't do this: `while(!(feof(pFile)))`, [**Read here for why**](http://stackoverflow.com/a/5432517/1322972) – WhozCraig Oct 07 '14 at 10:51

1 Answers1

0

Your file is organised in lines, so it's best to read it line-wise. The function for that is fgets, which will read a whole line of a certain maximum length into a char buffer. It keeps the terminating newline (unless the line is truncated because of the max length, but let's not deal with that right now). fgets returns the line buffer or NULL if the end of the file is reached.

Once you have a line, you must examine that line. Your lines all have the same syntax, namely

<action>, <amount>

so you could use sscanf, which isn't nice but quick and dirty. (scanfs error handling, for example, is very basic, so a good strategy is to ignore badly formatted lines altogether.)

The skeleton of your function might look like this:

int ledger(const char *fn)
{
    FILE *f;
    char line[80];              /* char buffer for line */
    int lineno = 0;             /* for error reporting */

    f = fopen(fn, "r");
    if (f == NULL) return -1;   /* error */

    while (fgets(line, sizeof(line), f)) {
        char action;
        double amount;
        int n;

        lineno++;
        n = sscanf(line, " %c, %lf", &action, &amount);

        if (n < 2) {
            printf("Skipping badly formatted line %d\n", lineno);
            continue;
        }

        /* Do stuff, e.g. just print */
        printf("%c, %16.2f\n", action, amount);
    }
    fclose(f);

    return 0;   /* success */
}
M Oehm
  • 28,726
  • 3
  • 31
  • 42