We help IT Professionals succeed at work.

Check out our new AWS podcast with Certified Expert, Phil Phillips! Listen to "How to Execute a Seamless AWS Migration" on EE or on your favorite podcast platform. Listen Now

x

Opening multiple files

sdickens
sdickens asked
on
Medium Priority
311 Views
Last Modified: 2010-04-15
I a writing this program and want to use  a switch statement to open different files using the same pointer.  For example if the user inputs January, I want the pointer to point to jan.dat, February--feb.dat, etc.  I also can't figure out how to keep a running total of a particular element in a structure.  Here is the code that I have written so far.  (In the file_ptr line, jan.dat is there just to get the program working.  I would like to total all the differences).
#include <stdio.h>
#include<stdlib.h>
#include <ctype.h>
#define days 31

FILE *OpenFile(char name[], char mode[]);

void ReadData(FILE *file_ptr);
void Display(FILE *file_ptr);

typedef
   struct
    {
      char date[4];
      float grossrec;
      float tokens;
      float stu_lunch;
      float stu_ala;
      float adult_lunch;
      float adult_ala;
      float other;
      float diff;
    }  ledger_t;

void main(void)
{
      float dummy;
      printf("Hi!  To begin entering daily info for your ledger, hit '1'");
      scanf("%f",&dummy);
      fflush(stdin);

      /*int month;
      char m1[10],lett[10];
      printf("Enter the month that you are working in.\n ");
      printf("1-Jan     2-Feb     3-Mar     4-Apr\n");
      printf("5-May     6-Jun     7-Jul     8-Aug\n");
      printf("9-Sep    10-Oct    11-Nov    12-Dec\nChoice: ");
      scanf("%d",&month);


       switch (month)
       {
       case 1:
            m1=="jan.dat";
            lett=="January";
            break;
       case 2:
            m1=="feb.dat";
            lett=="February";
            break;
       case 3:
            m1=="mar.dat";
            lett=="March";
            break;
       case 4:
            m1=="apr.dat";
            lett=="April";
            break;
       case 5:
            m1=="may.dat";
            lett=="May";
            break;
       case 6:
            m1=="jun.dat";
            lett=="June";
            break;
       case 7:
            m1=="jul.dat";
            lett=="July";
            break;
       case 8:
            m1=="aug.dat";
            lett=="August";
            break;
       case 9:
            m1=="sep.dat";
            lett=="September";
            break;
       case 10:
            m1=="oct.dat";
            lett=="October";
            break;
       case 11:
            m1=="nov.dat";
            lett=="November";
            break;
       case 12:
            m1=="dec.dat";
            lett=="December";
            break;
       default:
            printf("Please re enter your selection.\n");

       } */
       fflush(stdin);
       FILE *file_ptr;
       file_ptr=OpenFile("jan.dat","w+b");
                     /*wanted to put m1 in place of jan.dat here*/

      ReadData(file_ptr);
      Display(file_ptr);
      fclose(file_ptr);
}
FILE *OpenFile(char name[],char mode[])
{
      FILE *file_ptr;
      file_ptr=fopen(name,mode);
         if (file_ptr==NULL)
            {printf("Error opening file %s. \n",name);
             exit(1);
            }
      return file_ptr;
}

void ReadData(FILE *file_ptr)
{
     ledger_t entry;
     int ans;
     int count=0;

     printf("\nEnter daily totals:\n");
      do
       {
        count++;
        fflush(stdin);
        printf("Please enter the date (Day Only!): ");
        gets(entry.date);
        printf("Gross Receipts: ");
        scanf("%f",&entry.grossrec);
        printf("Tokens: ");
        scanf("%f",&entry.tokens);
        printf("Student Lunches: ");
        scanf("%f",&entry.stu_lunch);
        printf("Student ala carte: ");
        scanf("%f",&entry.stu_ala);
        printf("Adult Lunches: ");
        scanf("%f",&entry.adult_lunch);
        printf("Adult ala carte: ");
        scanf("%f",&entry.adult_ala);
        printf("Other: ");
        scanf("%f",&entry.other);
        fflush(stdin);

        fwrite(&entry,sizeof (ledger_t),1,file_ptr);

          if (count<days)
            do
             {printf("Do you want to make another entry?  (1--Yes/2--No)\n");
            printf("Choice: ");
            scanf("%d",&ans);
             }
            while ((ans!=1)&&(ans!=2));
      }
      while ((ans==1)&&(count<days));

         entry.date[0]='\0';
         for (;count<days;count++)
           fwrite(&entry,sizeof(ledger_t),1,file_ptr);
}
void Display(FILE *file_ptr)
{
      ledger_t entry;

      rewind(file_ptr);
      printf("\tWachusett Regional High School Ledger for \n\n");
      printf("Date| Gross     |Tokens |Student|Student|Adult  | Adult   |Other| Diff |\n");
      printf("    |Receipts   |       | Lunch |ala car|Lunch  |ala car  |     |      |\n");
      printf("------------------------------------------------------------------------\n");

       while (fread(&entry,sizeof(ledger_t),1,file_ptr))
        {entry.diff=((entry.tokens+entry.stu_lunch+entry.stu_ala+entry.adult_lunch
        +entry.adult_ala+entry.other)-(entry.grossrec));
          if (entry.date[0]!='\0')
            printf("%-3s|%.2f\t|%.2f\t|%.2f\t|%.2f\t|%.2f\t|%.2f\t|%.2f\t|%.2f\t|\n",entry.date,entry.grossrec,entry.tokens,entry.stu_lunch,entry.stu_ala,entry.adult_lunch,entry.adult_ala,entry.other,entry.diff);
        }


}
Thanks alot.  Shawn
Comment
Watch Question

Commented:
You cannot use assignment with arrays (not to mention you used '==' instead of '='). Therefore, to assign e.g. "jan.dat" to m1,
you should either use strcpy(m1, "jan.dat"); or declare m1 as a pointer: char *m1; (some compilers may require const char *m1;)
Commented:
Unlock this solution with a free trial preview.
(No credit card required)
Get Preview

Commented:
dickens -

mlev has hit most of the nail on the head... that == is just for checking for equality, like

  if(nVariable==5) { // ...

not for assignment, like

     nVariable=5;  // set nVariable to 5

I bet you started off with =, got errors and in a panic tried ==.  You don't get any errors with == because in c orphan expressions on their own are quite legal (and in this case quite nonfunctional)

mlev's solution of using strcpy() is the right way to go.

One tip on using char arrays, though... memory is now very cheap, you don't have to worry about saving a few bytes of stack space by being miserly with your arrays.  Your line

  char m1[10],lett[10];

although correct as it stands, leaves you open to crashing your program or randomly overwriting other stack variables if you ever increase the length of the filename strings copied into m1.  For example, if you ever changed to doing

  strcpy(m1, "c:\\mypath\\quite\\a\\long\\path\\myfile.dat");

then the copied string will burst through the measly 10 bytes you allocated to m1[] and copy the remaining text all over your other variables and return addresses on your stack.

The tip is to always allow at least 256 characters for any char array that will take a filename if you must use fixed char arrays.  Better yet, make a

  #define MY_MAX_FILEPATH_LENGTH 256

and use

  char m1[MY_MAX_FILEPATH_LENGTH];

. that way you can grow all the arrays containing file paths if you need to with just one edit.

C++ and MFC have since completely resolved this problem with a class called CString, but save that for another day.

Regards,

-Andy
Unlock the solution to this question.
Thanks for using Experts Exchange.

Please provide your email to receive a free trial preview!

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.