File Handling concept in C language is used for store a data permanently in computer. Using this concept we can store our data in Secondary memory (Hard disk). All files related function are available in stdio.h header file.
How to achieve File Handling in C
For achieving file handling in C we need follow following steps
- Naming a file
- Opening a file
- Reading data from file
- Writing data into file
- Closing a file
Functions use in File Handling in C
S.No | Function | Operation |
---|---|---|
1 | fopen() | To create a file |
2 | fclose() | To close an existing file |
3 | getc() | Read a character from a file |
4 | putc() | Write a character in file |
5 | fprintf() | To write set of data in file |
6 | fscanf() | To read set of data from file. |
5 | getw() | To read an integer from a file |
6 | putw() | To write an integer in file |
Defining and Opening a File
Data structure of file is defined as FILE in the standard I/O function. So all files should be declared as type FILE.
Before opening any file we need to specify for which purpose we open file, for example file open for write or read purpose.
Syntax
FILE *fp; pf=fopen("filename", "mode");
Here fp declare a variable as a pointer to the data type FILE.
Closing a File
A file must be close after completion of all operation related to file. For closing file we need fclose() function.
Syntax
fclose(Filepointer);
File Opening mode
S.No | Mode | Meaning | Purpose |
---|---|---|---|
1 | r | Reading | Open the file for reading only. |
2 | w | Writing | Open the file for writing only. |
3 | a | Appending | Open the file for appending (or adding) data to it. |
4 | r+ | Reading + Writing | New data is written at the beginning override existing data. |
5 | w+ | Writing + Reading | Override existing data. |
6 | a+ | Reading + Appending | To new data is appended at the end of file. |
Input/Output Operation on files
To perform Input/Output Operation on files we need below functions.
S.No | Function | Operation | Syntax | |
---|---|---|---|---|
1 | getc() | Read a character from a file | getc( fp) | |
2 | putc() | Write a character in file | putc(c, fp) | |
3 | fprintf() | To write set of data in file | fprintf(fp, "control string", list) | |
4 | fscanf() | To read set of data from file. | fscanf(fp, "control string", list) | |
5 | getw() | To read an integer from a file. | getw(fp) | |
6 | putw() | To write an integer in file. | putw(integer, fp) |
Write data in File
Example
#include<stdio.h> #include<conio.h> void main() { FILE *fp; char ch[20]; clrscr(); fp=fopen("hh.txt", "w"); printf("Enter any Text: "); scanf("%s",&ch); // Read data from keyboard fprintf(fp,"%s",ch); // Write data in file fclose(fp); getch(); }
No comments:
Post a Comment