Text format vs Binary formats

A file in the computer system is a container where a stream of bytes are stored. Now these streams of bytes can be in human-readable text format i.e. a series of ASCII characters or they can be a series of bytes which is not human readable. The human readable files are called text files. Notepad, VI editor and programming editors often creates these types of files. The files which are not text files can be considered as binary files. Binary files might contain computer records in bytes or other type of structured formats. C programming also handles these two types of files differently. Here in this tutorial we are discussing the binary mode of operations.

Binary file examples

  • Raw binary .bin or Data file .dat
  • Image/Photo files - example BMP, JPEG, GIF, PNG,
  • Audio files - example WAV, MP3, MIDI,
  • Video files - example AVI, MP4, MPEG, FLV, QuickTime movies
  • Database files
  • Office documents, DOC, EXCEL, PPTs
  • Executables - Applications (EXE), Dynamic Link Libraries (DLLs), System Files (sys),

Binary Mode operations in fopen

C programming language utilizes i/o library functions for handling file input and output operations. They are part of the standard input and output (stdio) module. The standard input output header file "stdio.h" should be included within the source file. It contains function prototypes for a group of file handling APIs (application programming interfaces). These functions comes under C standard library (stdlib). Fopen is the function used for opening a file stream in C program.

FILE* fopen (char * file_path, char * mode);

fopen function accepts the file path as a string and the mode of opening the file with one or two characters as a string. File can be in binary mode or text mode and we are mostly discussing the binary mode of operations in this article. Binary mode deals with data records and these records can be in the form of a single byte or several bytes. Most often structured objects are stored in binary mode and are stored sequentially.

Binary Mode fopen flags

The flag might contain 1-2 characters as string. Each character is in short hand form and represents the mode name. B - Stands for Binary. R - Stands for read, W - Stands for write, A - Stands for Append. The default is text mode unless B is specified in the flag.

#1 Binary Read (rb)
Opens a file in binary read mode
SYNTAX:
fp=fopen("binary.dat","rb");
#2 Binary write (wb)
Opens a file in binary write mode.
SYNTAX:
fp=fopen("binary.dat","wb");
#3 Binary append (ab)
Opens a file in binary append mode i.e. to add at the end of file.
SYNTAX:
fp=fopen("binary.dat","ab");
#4 Binary read+write (r+b)
Opens preexisting file in read and write mode.
SYNTAX:
fp=fopen("binary.dat","r+b");
#5 Binary write+read (w+b)
Open file for binary reading and writing also creates a new file if not exists.
SYNTAX:
fp=fopen("binary.dat","w+b");
#6 Binary append+write (a+b)
Opens file in append mode i.e. data can be written at the end of file.
SYNTAX:
fp=fopen("binary.dat","a+b");

File opening error handing (errno & strerror)

fopen should return a FILE pointer once the file is opened successfully else a NULL value is returned indicating a failure. We can check error number errno to know the error code associated with the previous failure of fopen. We can check the file pointer for NULL condition and throw an error string containing the error number. This error number may not be understood by users so that can be translated to a error string using strerror() function.

/* fopen() error handing using errorno */
#include <stdio.h>
#include <errno.h>
#include <string.h>

int main (int argc, char *argv[])
{
  FILE *fp;
  char *filepath = "file-not-found.txt";
  
  fp = fopen(filepath, "r");
  if(!fp)
  {
    printf("Error: fopen(%s) error number %d, %s.\n",
    filepath,
    errno,            /* fopen error number */
    strerror(errno)); /* Error string */
    return errno;
  }
  fclose(fp);
  return 0;
}

Error: fopen(file-not-found.txt) error number 2, No such file or directory.

A FILE pointer handle is returned by fopen, can be used for reading and writing file buffers from the application. C library has two API routines fread and fwrite. fread is to read records from the file and fwrite is to write records to a file.

File closing

A FILE pointer handle should be closed once it is no longer in use. We use fclose() library function to close the file pointer which was earlier opened using fopen(). fclose() works both for binary modes and text modes. A value of zero indicates the success of fclose() else fclose returns failures with a value of EOF.

int fclose(FILE *file_ptr);

Binary Mode fwrite

fwrite takes four arguments. First argument is the pointer where binary record is located. Next is the size of the record. Next to this is the number of records to write. Last argument is the file pointer. It returns the number of records written.

int fwrite (void * ptr, size_t record_size, size_t num_records, FILE * fp);

Binary Mode fwrite C code

/* Student Database Add records */
#include <stdio.h>

typedef struct _student_t
{
  char name[20];
  int roll;
  int std;

} student_t;
int main(int argc, char *argv[])
{
  FILE *fp;
  student_t s;
  memset(&s, 0, sizeof(s));
  fp = fopen ("records.dat", "wb");
  if(fp) {
    printf ("== Student Database Add records ==\n");
    printf ("Name : ");
    scanf ("%[^\n]", s.name);
    fflush (stdin);
    printf ("Roll : ");
    scanf ("%d", &s.roll);
    printf ("Std : ");
    scanf ("%d", &s.std);
    if (fwrite(&s, sizeof(s), 1, fp)) {
      printf ("Record added.");
    }
    fclose(fp);

  }
  return 0;
}

Output

== Student Database Add records ==
Name : Student 1
Roll : 1
Std : 1
Record added.

Binary Mode fread

fread takes identical arguments but the direction is read instead of write. First argument is the pointer where binary record is located. Next is the size of the record. Next to this is the number of records to write. Last argument is the file pointer. It returns the number of records read from the file.

int fread (void * ptr, size_t record_size, size_t num_records, FILE * fp);

Binary Mode fread C code

/* Student Database Display records */
typedef struct _student_t
{
  char name[20];
  int roll;
  int std;

} student_t;
int main(int argc, char *argv[])
{
    FILE *fp;
  student_t s;
  memset(&s, 0, sizeof(s));
  fp = fopen ("records.dat", "rb");
  if(fp) {
    printf ("== Student Database Display records ==\n");
    if (fread (&s, sizeof(s), 1, fp)) {
      printf ("Name : %s, Roll : %d, Std : %d\n", s.name, s.roll, s.std);
    }
    fclose(fp);

  }
  return 0;
}

Output

== Student Database Display records ==
Name : Student 1, Roll : 1, Std : 1

About our authors: Team EQA

You have viewed 1 page out of 252. Your C learning is 0.00% complete. Login to check your learning progress.

Further readings

How to open an existing file or create a new file?
C file operations, fopen library function, How to open an existing file or create a new file? Input parameters and output. Read, Write, Append, Binary, Text.

What is fdopen? How to reopen an existing file descriptor opened earlier with open/creat?
What is fdopen? How to reopen an existing file descriptor opened earlier with open/creat?

File write vs append mode|Append without in append mode.
What is the difference between write and append mode of fopen? Can I append a file without opening in append mode?

How does mode of file operation differ in binary and text mode?
How does mode of file operation differ in binary and text mode?

How to read/write files in formatted string mode?
How to read/write files in formatted string mode?

#