C Write File:
File handling simply means to open a file and to process it according to the required tasks. Writing data in a file is one of the common feature of file handling. In C, there are various modes that facilitates different ways and features of writing data into a file, including: w, r+, w+, a+, wb, rb+, wb+, or ab+ mode. C also supports some functions to write to a file.
C Write File functions are:
- C fprintf()
- C fputs()
- C fputc()
- C fputw()
C fputs() function:
To write a string (line of characters) into a file in C, fputs() function is used.
Syntax:
fputs(const char *s, FILE *stream)
Example 1: Example of fputs() function.
#include <stdio.h> void main() { FILE *f; f = fopen("file.txt", "w"); fputs("Reading data from a file is a common feature of file handling..",f); printf ("Data Successfully Written to the file!"); fclose(f); } |
Output
Data Successfully Written to the file! |
C Read File:
Reading data from a file is another common feature of file handling. In C, there are various functions that facilitates different ways and features of reading data from a file, including: reading all file data at a single go, reading the file data line by line and even to read the file data character by character.
C Read File functions are:
- C fscanf()
- C fgets()
- C fgetc()
- C fgetw()
C fgets() function:
To read a string (line of characters) from a file in C, fgets() function is used.
Syntax:
fgets(char *s, int n, FILE *stream)
Example 2: Example of fgets() function.
#include <stdio.h> void main() { FILE *f; f = fopen("file.txt", "w"); fputs("Reading data from a file is a common feature of file handling..",f); fclose(f); char arr[100]; f = fopen("file.txt","r"); printf("%s",fgets(arr,65,f)); fclose(f); } |
Output
Reading data from a file is a common feature of file handling.. |