Basics of File Handling in C


Here we will see some basic file handling operations in C. The operations are listed below:

  • Writing into a File
  • Reading from File
  • Appending in a File

Write into a file

See the code to get the idea how we write into a file

Example Code

#include <stdio.h>
int main() {
   FILE *fp;
   char *filename = "sample.txt";
   char *content = "Hey there! You've successfully created a file with content in c programming language.";
   /* open for writing */
   fp = fopen(filename, "w");
   if( fp == NULL ) {
      printf("%s: failed to open. 
", filename);       return -1;    } else {       printf("%s: opened in write mode.
", filename);    }    /* Write content to file */    fprintf(fp, "%s
", content);    if( !fclose(fp) )       printf("%s: closed successfully.
", filename);    return 0; }

Output

sample.txt: opened in write mode.
sample.txt: closed successfully.

2.Reading from a file

Se the code to get the idea how we read from a file Make a file (file_read.txt):

You have opened a file using C programming language, in read-only mode.

Example Code

#include <stdio.h>
int main() {
   FILE *fp;
   char *filename = "file_read.txt";
   char ch;
   /* open for writing */
   fp = fopen(filename, "r");
   if (fp == NULL) {
      printf("%s does not exists 
", filename);       return;    } else {       printf("%s: opened in read mode.

", filename);    }    while ((ch = fgetc(fp) )!= EOF) {       printf ("%c", ch);    }    if (!fclose(fp))       printf("
%s: closed.
", filename);    return 0; }

Output

file_read.txt: opened in read mode.
You have opened a file using C programming language, in read-only mode.
file_read.txt: closed.

3.Appending into a file

Se the code to get the idea how we can append lines into a file.

Make a file (file_append.txt)

This text was already there in the file.

Example Code

#include <stdio.h>
int main() {
   FILE *fp;
   char ch;
   char *filename = "file_append.txt";
   char *content = "This text is appeneded later to the file, using C programming.";
   /* open for writing */
   fp = fopen(filename, "r");
   printf("
Contents of %s -

", filename);    while ((ch = fgetc(fp) )!= EOF) {       printf ("%c", ch);    }    fclose(fp);    fp = fopen(filename, "a");    /* Write content to file */    fprintf(fp, "%s
", content);    fclose(fp);    fp = fopen(filename, "r");    printf("
Contents of %s -
", filename);    while ((ch = fgetc(fp) )!= EOF) {       printf ("%c", ch);    }    fclose(fp);    return 0; }

Output

Contents of file_append.txt -
This text was already there in the file.
Appending content to file_append.txt...
Content of file_append.txt after 'append' operation is -
This text was already there in the file.
This text is appeneded later to the file, using C programming.

Updated on: 18-Nov-2020

839 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements