written 8.3 years ago by | • modified 8.3 years ago |
- In C programming, file is a place on disk where a group of related data is stored.
- When the program is terminated, the entire data is lost in C programming.
- If you want to keep large volume of data, it is time consuming to enter the entire data.
- But, if file is created, this information can be accessed using few commands.
- There are large numbers of functions to handle file I/O in C language.
- High level file I/O functions can be categorized as: Text file & Binary file.
File Operations:
- Creating a new file.
- Opening an existing file.
- Reading from and writing information to a file.
- Closing a file.
Modes in which file can opened:
The allowed modes for fopen are as follows:
r - open for reading
w - open for writing (file need not exist)
a - open for appending (file need not exist)
r+ - open for reading and writing, start at beginning
w+ - open for reading and writing (overwrite file)
a+ - open for reading and writing (append if file exists)
Functions to read and write files are:
fputc ():
- This function is used to put a character type data into the opened file using the fopen() function, pointed by a file pointer.
- The characters to be put into a file as well as the file pointer are to be passed as the parameters to this function.
Syntax: fputc(<char type="" data="">, <file pointer="" identifier="">);
Example: fputc(c, fp);
getc ():
- This function is used to get a character from the file pointed by the corresponding file pointer passed to the function.
- It is exactly opposite the fputc function.
Syntax: getc(file pointer identifier>);
Example: getc(fp);
fprintf ():
- This function is used to store the different data types in the file as the fputc() function is used to store the character in the file.
- This can be used to store integer, float, string etc types of data into the file opened.
Syntax: fprintf(<file pointer="" identifier="">, “<format specifiers="">”, <variable names="">);
Example: fprintf(fp, “%d”, x);
fscanf ():
- This function is used to read the different types of data as the getc() function is used to read a character from the file.
- This function can be used to read an integer, float string etc types of dara into the file opened.
Syntax:
fscanf(<file pointer="" variable="">, “<format specifiers="">”, <address of="" the="" variables="" in="" which="" the="" data="" is="" to="" be="" read="">);
Example:
fscanf(fp, “%d”, &x);