File Handling in C Language


File Handling in C 


Why Files are Needed?




When a program is terminated, the entire data is lost. Storing in a file will preserve your data even if the program terminates. If you have to enter a large number of data, it will take  a lot of time to enter them all. However, if you have a file containing all the data, you can easily access the contents of the file using few commands in C. You can easily move your data from one computer to another without any changes .

Types of files 


When dealing with files, there are two types of files you should know about:

1- Text Files
2- Binary Files

Text Files


Text files are the normal.txt files that you can easily create using Notepad or any simple text editors.
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 least security and takes bigger storage space.

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 higher amount of data, are not readable easily and provides a better security than text files.

File Operations 


In C, you can perform four major operations on the file, either text or binary:

1-Creating a new file

2- Opening an existing file

3- Closing a file

4- Reading from and writing information to a file

Working with Files 


When working with files, you need to declare a pointer of type file. This declaration is needed for communication between the file and program.
FILE *fptr;

Opening  A File - For creation and edit 


Opening a file is performed using the library function in the 'stdio.h' header file: fopen().

Syntax of Opening a file 


ptr - fopen("fileopen", "mode")

Example:--


Write a program to write 'HELLO STUDENTS in a file.


file handling in c, example of file handling in c
example file handling

Note --

We discus later all mode of file but in above example let's suppose the f1.txt doesn't exist in the location c:\cprogram. The first function creates a new file named f1.txt and opens it for writing as per the mode 'w'.
The writing mode allows you to create and edit (overwrite) the contents of the file.

Closing a file 


The file (both text and binary) should be closed after reading/writing.

Closing a file is performed using library function fclose().

fclose(fptr);  // fptr is the file pointer associated with file to be closed.

Comments

Popular posts from this blog

Notepad, Wordpad and Paint

O LEVEL- INTERNET TECHNOLOGY & WEB DESIGN

O LEVEL- INTERNET TECHNOLOGY & WEB DESIGN