File handling in C involves performing operations on files—reading data from files, writing data to files, modifying file content, and managing files. The standard C library provides functions and types to handle files.

Firstly a file pointer must be created to access a file

Below is a C program that reads and writes content into a file:





 

Below Program appends the contents of a file to another file stored on desktop

 

#include <stdio.h>

#include <stdlib.h> // For exit()

 

int main()

{

FILE *fp1, *fp2;

char fname1[50] , fname2[50] , c;

printf("Enter file name to open for reading : ");

scanf("%s", fname1);

 

// Open one file for reading

 

fp1 = fopen(fname1, "r");

if (fp1 == NULL)

{

printf("%s file does not exist..", fname1);

exit(0);

}

 

printf("\nEnter filename to append the content : ");

scanf("%s", fname2);

 

// Open another file for appending content

fp2 = fopen(fname2, "a");

if (fp2 == NULL)

{

printf("%s file does not exist...", fname2);

exit(0);

}

 

// Read content from file

c = fgetc(fp1);

while (c != EOF)

{

fputc(c,fp2);

c = fgetc(fp1);

}

printf("\nContent in %s appended to %s", fname1,fname2); fclose(fp1); fclose(fp2); return 0;

}

 

Output: