CodeSteps

Python, C, C++, C#, PowerShell, Android, Visual C++, Java ...

C Programming – Dealing with files – How to write to the file?

We have discussed opening & reading from the file in our previous Article “C Programming – Dealing with files – How to read from a file?“.

fwrite function

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 the same as fread function. fread reads from the file; whereas fwrite writes to the file.

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

Through the third argument “size_t ntimes“, we need to pass a number of times to write the chunks to the file. And the last argument “FILE *fp“, is the valid file pointer; which gets it from the previous successful call to fopen function.

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

fseek function

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

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

First parameter “FILE *stream“, 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 the beginning of the file, to end of the file, from the current position of the file position indicator and the valid values are SEEK_BEG, SEEK_END, and SEEK_CUR respectively.

This function is most useful when we deal with records in the files; records are data blocks used to store related information in the files. For example, employee records are used to store Employee related information.

In our previous article, we have seen an example that reads the content of the file and displays it on the screen. We have opened the file as a text file.

Another important file type 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 in machine-readable form. A simple example is, executable files (.EXE files) are binary files, and “.TXT” files are text files.

Usually, binary files will occupy less disk space 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.

Dealing with records

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

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

  • Employee Name – It is a text field containing a 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 in the “employee.dat” file.

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

Requirement 4. The program should be able to display the Nth record from the “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 the user provided the information, store the information into the “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 the user requested. Assume user may enter employee number to retrieve employee record.
  • Retrieve the Nth record from the database file “employee.dat” and display the Nth record information on the screen.

Let’s write our program:

Step 1. Based on the above requirement, we understand that we have to use employee records to maintain employee information. So, here I am going to use ‘C’ structures to maintain employee records. ‘C’ structures are a group of related fields. ‘C’ structures are created by using the struct keyword. The ‘C’ code for our employee record 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 reading, write binary mode. Below is the 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 does not exist, we will use fwrite function to add the record at the end of the file.
  • If the record 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 the above code; “temp” and “emp” are the variables of type “struct Employee”. “getrecord” is our function which checks into the “employee.dat” file whether the employee record with the given employee ID exists or not.

Note that, I am not going to give the code of “getrecord” in this article. We will discuss 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 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");

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

Step 6. If the user wants to Quit the application, he can enter option 3. Make sure that the file “employee.dat” should be closed properly before exiting the application.

Let’s discuss more in our next article.

// Malin

C Programming – Dealing with files – How to write to the file?

2 thoughts on “C Programming – Dealing with files – How to write to the file?

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top
Exit mobile version