File handling in C

Data Manipulation

Reading and Writing File
We can read data from file and write data to file in many ways.

Reading or writing characters using fgetc() and fputc() functions.

getc() This function helps us to read a single character from the file.
ch=getc(fp);
ch: is char type variable to store the character read from the file.
fp: is the file pointer used to open the file.
putc() This function helps us to write a single character in the file.
putc(ch,fp);
ch: character to write in the file.
fp : is the file pointer used to open the file.

Note: The file pointer moves by one character position for every operation of getc() or putc(). The getc() will return an end-of-file marker EOF, when end of file has been reached. Therefore ,the reading operations should be terminated when EOF is encountered.

Reading or writing string using fgets() and fputs() functions.

fputs() The fputs() function is used to write string(array of characters) to the file.
Syntax:
fputs(char str[], FILE *fp);
The fputs() function takes two arguments, first is the string to be written to the file and second is the file pointer where the string will be written.
fgets() The fgets() function is used to read string(array of characters) from the file.
Syntax:
fgets(char str[],int n,FILE *fp);
The fgets() function takes three arguments, first is the string read from the file, second is size of string(character array) and third is the file pointer from where the string will be read.
The fgets() function will return NULL value when it reads EOF(end-of-file).

Reading or writing integers using getw() and putw() functions.

putw() The putw() function is used to write integers to the file.
Syntax
putw(int number, FILE *fp);
The putw() function takes two arguments, first is an integer value to be written to the file and second is the file pointer where the number will be written.
getw() The getw() function is used to read integer value form the file.
Syntax
int getw(FILE *fp);
The getw() function takes the file pointer as argument from where the integer value will be read and returns returns the end-of-file if it has reached the end of file.