Unit 10 File Handling
Unit 10 File Handling
1. Text files
• Text files are the normal .txt files. You can easily create text files using any simple text editors such as
Notepad.
• When you open those files, you'll see all the contents within the file as plain text. You can easily edit or
delete the contents.
• They take minimum effort to maintain, are easily readable, and provide the least security and takes
bigger storage space.
Binary files
2. Binary files
• Binary files are mostly the .bin files in your computer.
• Instead of storing data in plain text, they store it in the binary form (0's and 1's).
• They can hold a higher amount of data, are not readable easily, and provides better
security than text files.
File Operations
• One should always close a file whenever the operations on file are over. It
means the contents and links to the file are terminated. This prevents
accidental damage to the file.
FILE *fp;
fclose (file_pointer); fp = fopen ("data.txt", “w”);
fclose (fp);
Writing data to a file
• In C, when you write to a file, newline characters '\n' must be explicitly added.
• fputc(char, file_pointer):
It writes a character to the file pointed to by file_pointer.
• fputs(str, file_pointer):
It writes a string to the file pointed to by file_pointer.
• fprintf(file_pointer, str, variable_lists):
It prints a string to the file pointed to by file_pointer. The string can optionally include format
specifiers and a list of variables variable_lists.
Reading data from file
• We can read content of a file in c using the fscanf() and fgets() and fgetc() functions. All are used
to read contents of a file.
• fgetc(file_pointer):
It returns the next character from the file pointed to by the file pointer. When the end of the file
has been reached, the EOF is sent back.
• fgets(buffer, n, file_pointer):
It reads n-1 characters from the file and stores the string in a buffer in which the NULL
character '\0' is appended as the last character.
• fscanf(file_pointer, conversion_specifiers, variable_adresses):
It is used to parse and analyze data. It reads characters from the file and assigns the input to a list
of variable pointers variable_adresses using conversion specifiers. with scanf, fscanf stops
reading a string when space or newline is encountered.