Data Files
  • Using Files in C
  • File Types
  • Text Files
  • Binary Files
  • Working with text files and Binary Files
    • Opening and Closing Files
    • Writing and Reading Data to or from data files
    • File opening modes
  • File operations using std. library and system calls
  • File management I/O functions
  • Random Access Files
  • Error Handling
Board Exam Theory Questions
  1. There are many I/O functions in the C library which are given below.

    Function Description Example
    Character I/O function fputc Used to write a character to a file. fputc(ch,fp)
    fgetc Used to read a character from a file. ch = fgetc(fp)
    String Input/Output function fputs Used to write a string to a file. fputs(ch,fp)
    fgets Used to read a string from file. fgets(ch,50,fp)
    Formatted Input/Output function fprintf() Used to write integer, float, char or string data to a file. fprintf(fp, "%s%d%f", s.name, s.rollno, s.marks)
    fscanf() Used to read integer, float, char or string value from a file. fscanf(fp, "%s%d%d", &s.name, &s.age, &s.marks)
    Record Input/Output function fwrite() Used for record output fwrite(&s, sizeof(s) ,1 ,fp)
    fread() Used for record input. fread(&s, sizeof(s) ,1 ,fp)


  2. File handling operations may fail due to anyone of the following reasons:
    1. A file for reading may not be present on the disk.
    2. Insufficient disk space for opening a file for writing.
    3. Write protected disk does not allow storage of data on it.
    4. Dealing with corrupt file.

    To handle these error we need to check whether the intended data files has opened successfully or not by comparing the result of fopen() function with NULL character. fopen() function points to the beginning of the file if file is opened successfully otherwise it returns NULL.

    Code for handling error during file opening.
    Other useful functions for hanlding error during read/write operations are:
    ferror() This function reports any error during a read/write operation on a file. Its prototype is: int ferror(file_pointer_variable);
    perror() This function writes the error message specified by the compiler. Its prototype is: void perror(error_message);
  3. There is no need to read each record sequentially, if we want to access a particular record. C supports these functions for random access file processing.

    1. fseek()
    This function is used for seeking the pointer position in the file at the specified byte.

    Syntax: fseek( File pointer, Displacement, pointer position); Example: fseek(fp, 10L, 0) where
    File pointer: It is the pointer which points to the file.
    Displacement: It is positive or negative, attached with L because this is a long integer.
    Pointer position: This sets the pointer position in the file whose value can be 0 (Beginning), 1 (Current) or 2 (End of file).

    2. ftell()
    This function returns the value of the current pointer position in the file.The value is count from the beginning of the file.

    Syntax: ftell(fp);
    3. rewind()
    This function is used to move the file pointer to the beginning of the given file.

    Syntax: rewind( fp);
  4. Define opening and closing a file along with suitable examples. [4] [070]
  5. What is a data file in C? What are the modes in file handling? Explain briefly. [1+3] [072]
  6. List different types of standard I/O used in C. [2] [072]
  7. Differentiate between text file and binary file. [2] [069]
  8. What do you mean by opening a data file? How is this accomplished? Explain fscanf, fprintf, fread, fwrite functions. [1+3+4] [068]

Background

The program that we have executed so far accepts data from the keyboard and gives output to visual display unit. This type of I/O is called console I/O. The console input/output work fine as long as the data is small. It becomes very inconvenient and time consuming to handle the large volume of data through console I/O. And the data get lost or destroy when the program is terminated or the computer system is turn off.

To overcome these problems, here comes the need of file handling in C.

File handling in C enables us to create, write, read and update the files stored on the local file system through our C program. The basic steps for using a File in C are always the same.

  1. 1. Create a variable of type "FILE*"
  2. 2. Open the file using the "fopen()" function ans assign the "file" to the variable.
  3. 3. Check to make sure the file was successfully opened by checking to see if the variable == NULL. If it does, an error has occured.
  4. 4. Use the Input/Output file handeling function to write/read from the file. Usually these function calls are placed in a loop.
  5. 5. Closing the file.


1. Creating a variable of type "FILE*"

While working with data file, we need buffer area (i.e, temporary memory) where information is stored for short period of time in the course of transferring data between computer memory and data file. The buffer area is established by creating a variable of type "FILE*"



Here, FILE is a special structure (keyword), declared in header file stdio.h and *fp is file pointer variable that stores the beginning address of the buffer area allocated after a file has been opened. Also file pointer contains other information about the file including file_name, new position of the file, whether the file is being read or written, and whether errors or end-of-file have occured. Basically file pointer acts as a communication link between the program and the file.

2. Opening the file using fopen()

Before performing an input/output function in file, a file must be opened. The fopen() function is used to open a file defined in the stdio.h header file. The syntax of the fopen() is given below:



The function fopen() returns a pointer to the beginning of the buffer area associated with the file (i.e. the first address of the allocated buffer area is stored in pointer variable *pt). The fopen() function accepts two arguments.
  1. The first is the name of the file. If the file is stored at some specific location, then we must mention the path at which the file is stored. For example, a file can be like “D:\\Student.txt”.
  2. And second is the mode in which file is to be opened. It is also string.
We can use one of the following modes in the fopen() function.
Mode Binary Mode Meaning of Mode During Existence of file Pointer Position During Inexistence of file
w wb Opens new file for writing mode. If the file exists, its contents are destroyed. At the beginning of the file If the file does not exit, it will be created.
r rb Opens file for reading mode. If the file exists, its contents are not destroyed. At the beginning of the file If the file does not exist, fopen() returns NULL.
a ab Opens file for appending mode. If the file exists, its contents are not destroyed. At the end of the file. If the file does not exist, it will be created.
w+ w+b or wb+ Opens file for both writing and reading. If the file exists, its contents are destroyed. At the beginning of the file If the file does not exist, it will be created.
r+ r+b or rb+ Opens file for both writing and reading purpose. If the file exists, its contents are not destroyed. At the beginning of the file. If the file does not exist, fopen() returns NULL.
a+ a+b or ab+ Opens file for both reading and appending purpose. If the file exists, its contents are not destroyed. The initial file position for reading is at the beginning of the file,
but output is always appended to the end of the file.
If the file does not exist, new file will be created.

Note: The distinguishing feature of a file is its end-of-file mark. We refer to this mark as EOF. EOF typically has the value -1.




3. Error Handling in File Operations (Updated)

File handling operations may fail due to anyone of the following reasons:
  1. A file for reading may not be present on the disk.
  2. Insufficient disk space for opening a file for writing.
  3. Write protected disk does not allow storage of data on it.
  4. Dealing with corrupt file.
To handle these error we need to check whether the intended data files has opened successfully or not by comparing the result of fopen() function with NULL character. Since fopen() function points to the beginning of the file if file is opened successfully otherwise it returns NULL.

Code for handling error during file opening.



Other useful functions for hanlding error during read/write operations are:
ferror() This function reports any error during a read/write operation on a file. Its prototype is: int ferror(file_pointer_variable);
perror() This function writes the error message specified by the compiler. Its prototype is: void perror(error_message);

Note: Exit is a jump statement in C which takes an integer (zero or non-zero) to represent different exit status. Exit Success is indicated by exit(0) statement which means successful termination of the program. Exit Failure is indicated by exit(1) which means the abnormal termination of the program. We can use different integer other than 1 to indicate different types of errors.


4. File Handling Input/Output function


There are many I/O functions in the C library which are given below.

Function Description Example
Character I/O function fputc Used to write a character to a file. fputc(ch,fp)
fgetc Used to read a character from a file. ch = fgetc(fp)
String Input/Output function fputs Used to write a string to a file. fputs(ch,fp)
fgets Used to read a string from file. fgets(ch,50,fp)
Formatted Input/Output function fprintf() Used to write integer, float, char or string data to a file. fprintf(fp, "%s%d%f", s.name, s.rollno, s.marks)
fscanf() Used to read integer, float, char or string value from a file. fscanf(fp, "%s%d%d", &s.name, &s.age, &s.marks)
Record Input/Output function fwrite() Used for record output fwrite(&s, sizeof(s) ,1 ,fp)
fread() Used for record input. fread(&s, sizeof(s) ,1 ,fp)




5. fclose() function

The fclose() function is used to close a file. The file must be closed after performing all the operations on it. Closing a file ensures that all outstanding information associated with the file is flushed out from the buffers and all links to the file are broken. It also prevents any accidental misuse of the file. The syntax of fclose() function is given below.



Note: If the file is open for writing or appending, fclose() writes any data remaining in the file's buffer to the file and appends the end of file (EOF) mark after the last character written. If the file is open for reading, fclose() ignores any data left in the file's buffer and closes the connection. fclose() returns 0 if successful, EOF if unsuccessful. fclose() fails if the storage device is full, an I/O error occurs or the storage medium is prematurely removed.

fputc() and fgetc() function

  1. WAP to create a file in "w" mode. Perform writing operation using fputc() function.
  2. WAP to open a file in "r" mode. Perform reading operation using fgetc() function.
  3. WAP to open a file in "a" mode. Perform appending operation using fputc() function.
  4. WAP to create a file in "w+" mode. Perform writing and reading operation using fputc() and fgetc() function respectively.
  5. WAP to open a file in "r+" mode. Perform writing and reading operation using fputc() and fgetc() function respectively.
  6. WAP to open a file in "a+" mode. Perform appending and reading operation using fputc() and fgetc() function respectively
  7. Write a program to read the information of a file named “data.txt” and write its contents to another file”record.txt”. [6] [2072]

fputs() and fgets() function

  1. WAP to create a file in "w+" mode. Perform writing and reading operation using fputs() and fgets() function respectively.

fprintf() and fscanf() function

  1. WAP to enter name, rollno and marks of 5 students and store them in file. Read and display the same file.
  2. Write a program in C to read integers from user until user says “no”. After reading the data write all the odd numbers to a file name odd.txt and all the even number to file name even.txt. [6] [069] [074]

fwrite() and fread() function

  1. WAP to enter name, rollno and marks of 5 students and store them in file. Read and display the same file.
  2. Write a program to write name, roll no and age of five students into a disk file name “STUDENT.DAT”. [6] [2072]
  3. WAP to enter name, roll no & age of 5 students and store them in file name “STUDENT.DAT”. Read & display the content of the file.
  4. Write a program to read name and roll number of 5 students from user and store them in file. If the file already contains data, your program should add new data at the end of the file. [6] [073]
  5. WAP that first appends records of five employees in a binary file and display the contents from file. The file name should be given by user and display message if it does not exist. [6]
Web hosting by Somee.com