FILE HANDLING
In programming, we may require some specific input data to be generated several numbers of times. File Handling in C enables us to create, update, read, and delete the files stored on the local file system through our C program.
The following operations can be performed on a file
- Creating a new file.
- Opening an existing file.
- Closing a file.
- Reading from and writing to a file.
OPENING and CLOSING A FILE-
Opening a file is performed using the fopen() function defined in the stdio.h header file. Closing a file is performed using the fclose() function.
Example:-
ptr = fopen("fileopen", "mode"); //for opening
fopen("E:\\cprogram\\newprogram.txt", "w"); //for opening
fclose(fptr); // for closing
READING and WRITING A FILE-
For reading and writing to a text file, we use the functions fprintf() and fscanf(). These functions just file versions of printf() and scanf().
Writing a file
#include<stdio.h>
void main()
{
FILE *fp;
fp = fopen("file.txt", "wt");
fprintf(fp, "Thisis testing for fprintf....\n");
fputs("This is testing for fputs..\n", fp);
fclose(fp);
}
The function fputs() writes the string s to the output stream referenced by fp. It returns a non-negative value on success, otherwise EOF is returned in case of any error.
Reading a file
#inlcude<stdio.h>
int main()
{
FILE *fp;
char str[60];
fp = fopen("file.txt", "r");
if(fp == NULL)
{
perror("error opening file");
return(-1);
}
if(fgets(str, 60, fp)!=NULL)
{
puts(str);
}
fclose(fp);
return(0);
}
The fgetc() function reads a character from the input file referenced by fp. The return value is the character read, or in case of any error, it returns EOF.
0 Comments
Doubts? Please let our team know So that we can serve you better.