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


Opening multiple files

sdickens asked
Medium Priority
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 <ctype.h>
#define days 31

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

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

      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'");

      /*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: ");

       switch (month)
       case 1:
       case 2:
       case 3:
       case 4:
       case 5:
       case 6:
       case 7:
       case 8:
       case 9:
       case 10:
       case 11:
       case 12:
            printf("Please re enter your selection.\n");

       } */
       FILE *file_ptr;
                     /*wanted to put m1 in place of jan.dat here*/

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

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

     printf("\nEnter daily totals:\n");
        printf("Please enter the date (Day Only!): ");
        printf("Gross Receipts: ");
        printf("Tokens: ");
        printf("Student Lunches: ");
        printf("Student ala carte: ");
        printf("Adult Lunches: ");
        printf("Adult ala carte: ");
        printf("Other: ");

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

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

         for (;count<days;count++)
void Display(FILE *file_ptr)
      ledger_t entry;

      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");

       while (fread(&entry,sizeof(ledger_t),1,file_ptr))
          if (entry.date[0]!='\0')

Thanks alot.  Shawn
Watch Question

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;)
Unlock this solution with a free trial preview.
(No credit card required)
Get Preview

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


and use


. 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.


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.


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.