C Programming: Dealing with files (Part – 2)

Another important buffered function ‘C’ provides is fwrite function. fwrite function writes to the file. The file should be opened with fopen function call. The syntax of this fwrite function is:

size_t fwrite(const void *ptr, size_t size, size_t ntimes, FILE *fp);

The syntax is same like fread function. fread reads from file whereas fwrite writes to the file.

First parameter “const void *ptr” is points to the address of the data you want to store into the file. Data will be stored as chunks. Size of the chunk should be mentioned in second argument “size_t size”.

Through third argument we need to pass number of times to write the chunks to the file. And the last argument is the valid file pointer. Its get it from the previous successful call to fopen function.

On success fwrite function will returns the number of bytes written into the file. There are several reasons to fail this function; like disk is full, no access to write to the file etc.,.

Another interesting function is fseek. fseek function allows to move the file position indicator to a new location. The position of current file position indicator is depends on it last I/O operation. This function is useful when you want to read from or write to particular position in the file. The syntax of this function is:

int fseek(FILE *stream, long offset, int origin);

First parameter is the valid file pointer, usually we will get it from fopen function call. “offset” is offset bytes to move the file position indicator. “origin” from where to move the file position indicator. It could be from beginning of the file, to end of the file, from current position of the file position indicator and the valid values are SEEK_BEG, SEEK_END and SEEK_CUR respectively. This function is mostly useful when we dealing with records in the files; records are data blocks used to store related information in the files. For example: employee record used to store an Employee related information.

In our previous article, we have seen an example which reads content of the file and display it on the screen. We have opened the file as a text file. Another important file types we can deal with these I/O functions is binary files. Unlike text files where information is stored in human readable form whereas binary files stores the information in binary format which is I machine readable form. Simple example is, executable file (.EXE files) are binary files and “.TXT” files are text files. Usually binary files will occupy less disk space over the text files. For example: if we want to store a big number “2147483647” in a text file, it will occupy 10 bytes whereas to store the same number in a binary file, it occupies only 4 bytes (depends on your system) of memory.

As I mentioned earlier, with these file handling functions we can deal with both text and binary files. Lets take a simple code example. Here I am going to create a simple employee information database where the data will be stored into a “employee.dat” binary file. Below are the requirements:

Requirement 1. Maintain a employee record information in the file. Each employee record contains the following fields:

  • Employee Name – It is a text field contains maximum of “50” characters.
  • Age – It is an integer field.
  • Employee Number – It is also an integer field.
  • Salary – It is a floating point number.

Requirement 2. Employee information can be taken from the user and stored it into the “employee.dat” file.

Requirement 3. Whenever requested the information for an employee, it should read the data from “employee.dat” file and display the information on the screen.

Requirement 4. The program should be able to display Nth record from “employee.dat” file.

These are the details we have to create our simple program. With these details we came to know the following things:

  • Collect the employee information from the user.
  • Once user provided the information, store the information into “employee.dat” file as an employee record.
  • Maintain an employee record and store/retrieve employee details to/from the database “employee.dat” file.
  • Retrieve the employee record whenever user requested. Assume user may enter employee number to retrieve employee record.
  • Retrieve Nth record from the database file “employee.dat” and display the Nth record information on the screen.

Lets write our program:

Step 1. Based on above requirement, we understand that we have to use employee record to maintain employee information. So, here I am going to use ‘C’ structures to maintain employee record. ‘C’ structures are group of related fields. ‘C’ structures are created by using struct keyword. The ‘C’ code for our employee record is looks like below:

   struct Employee
   {
      char Name[50];
      int ID;
      int Age;
      float Salary; 
   };

Step 2. We have to create a binary file “employee.dat” to maintain employee record information. Create the file using File Manager. Then we will use fopen to open an existing file. We have to do read and write file operations on the file; so, we open the file in read, write binary mode. Below code do this:

   FILE *fp = fopen("employee.dat", "rb+");

Step 3. Now we need to take the inputs from the user. Based on the user inputs, we have to add/update employee records in the “employee.dat” file and fetch the requested employee record and display it on the screen. This should repeat until the user wants to Quit from the application. The code looks like below:

   // Take inputs from the user
   do
   {
      printf("Enter your option here:\n");
      printf("1. Add/Update Employee Record.\n");
      printf("2. Fetch Employee Record.\n");
      printf("3. Quit.\n");
      
      scanf("%d", &option);

      switch ( option )
      {
         // Add/Update Employee Record.
         case 1:
               {
                  // Add the functionality here to:
                  // Add/Update an employee record.
               }
               break;

         // Fetch Employee Record.
         case 2:
               {
                  // Add the functionality here to:
                  // Fetch Employee Record and display the information on the screen.
               }
               break;

         // Prepare for Quit. Do nothing.
         case 3: break;

         // Invalid input.
         default:
                {
                   printf("WARNING! Invalid option.\n");
                }
      }
   }
   while ( option != 3 );

Step 4. When the user wants to add or update an employee record:

  • First we need to check the record already exists in the “employee.dat” file, based on employee ID.
  • If it not exists, we will use fwrite function to add the record at the end of the file.
  • If the record is already exists, we need to find the location where it is in the file “employee.dat”. We will update the same record using fwrite function.
                  long position = getrecord(emp.ID, &temp);
                  if ( position >= 0 )
                     fseek(fp, position, 0);
                  else
                     fseek(fp, 0L, SEEK_END);

                  fwrite(&emp, sizeof(emp), 1, fp);
                  fflush(fp);

From above code “temp” and “emp” are the variables of type “struct Employee”. “getrecord” is our function which checks into “employee.dat” file whether the employee record with the given employee ID is exists or not.

I am not going to give the code of “getrecord” in this article. We will discuss about the “getrecord” code in the next article along with ‘C’ function fflush.

Step 5. If the user wants to see employee information of an employee:

  • Check in the “employee.dat” file for an employee information with the given employee ID.
  • Display the information on the screen.
                  int empid = -1;

                  printf("Enter Employee ID to fetch the details:\n");
                  scanf("%d", &empid);

                  struct Employee emp;                  
                  
                  long position = getrecord(empid, &emp);
                  if ( position != -1 )
                  {
                     printf("Below are the requested Employee's details:\n");
                     printf("\t> Employee Name: %s\n", emp.Name);
                     printf("\t> Employee ID: %d\n", emp.ID);
                     printf("\t> Employee Age: %d\n", emp.Age);
                     printf("\t> Employee's Salary: $%.2f\n", emp.Salary);
                  }
                  else
                     printf("ERROR: Employee Record doesn't exists.\n");

Above code is self-explanatory. So, I am not giving any comments here.

Step 6. If the user wants to Quit from the application, exit from the application. Make sure that the file “employee.dat” should be closed properly before exiting the application.

Lets discuss about more in our next article.

// Malin

1 comment for “C Programming: Dealing with files (Part – 2)

Leave a Reply