FILE HANDLING IN C

File Handling concept in C language is used for store a data permanently in computer. Using this concept we can store our data in Secondary memory (Hard disk). All files related function are available in stdio.h header file.

How to achieve File Handling in C

For achieving file handling in C we need follow following steps

Functions use in File Handling in C

S.No

Function

Operation

1

fopen()

To create a file

2

fclose()

To close an existing file

3

getc()

Read a character from a file

4

putc()

Write a character in file

5

fprintf()

To write set of data in file

6

fscanf()

To read set of data from file.

5

getw()

To read an integer from a file

6

putw()

To write an integer in file

Defining and Opening a File

Data structure of file is defined as FILE in the standard I/O function. So all files should be declared as type FILE.

Before opening any file we need to specify for which purpose we open file, for example file open for write or read purpose.

Syntax

FILE *fp;

pf=fopen("filename", "mode");

Here fp declare a variable as a pointer to the data type FILE.

Closing a File

A file must be close after completion of all operation related to file. For closing file we need fclose()function.

Syntax

fclose(Filepointer);

File Opening mode

S.No

Mode

Meaning

Purpose

1

r

Reading

Open the file for reading only.

2

w

Writing

Open the file for writing only.

3

a

Appending

Open the file for appending (or adding) data to it.

4

r+

Reading + Writing

New data is written at the beginning override existing data.

5

w+

Writing + Reading

Override existing data.

6

a+

Reading + Appending

To new data is appended at the end of file.

Input/Output Operation on files

To perform Input/Output Operation on files we need below functions.

S.No

Function

Operation

Syntax

1

getc()

Read a character from a file

getc( fp)

2

putc()

Write a character in file

putc(c, fp)

3

fprintf()

To write set of data in file

fprintf(fp, "control string", list)

4

fscanf()

To read set of data from file.

fscanf(fp, "control string", list)

5

getw()

To read an integer from a file.

getw(fp)

6

putw()

To write an integer in file.

putw(integer, fp)

Write data in File

Example

#include<stdio.h>

#include<conio.h>

void main()

{

FILE *fp;

char ch[20];

clrscr();

fp=fopen("Hello.txt", "w");// Creates in same Directory where ur C File is Saved

printf("Enter any Text: ");

scanf("%s",&ch); // Read data from keyboard

fprintf(fp,"%s",ch); // Write data in file

fclose(fp);

getch();

}

. Write a C program to read name and marks of n number of students from user and store them in a file.

#include <stdio.h>

int main()

{

   char name[50];

   int marks, i, num;

   printf("Enter number of students: ");

   scanf("%d", &num);

   FILE *fptr;

   fptr = (fopen("C:\\student.txt", "w"));

   if(fptr == NULL)

   {

       printf("Error!");

       exit(1);

   }

   for(i = 0; i < num; ++i)

   {

      printf("For student%d\nEnter name: ", i+1);

      scanf("%s", name);

      printf("Enter marks: ");

      scanf("%d", &marks);

      fprintf(fptr,"\nName: %s \nMarks=%d \n", name, marks);

   }

   fclose(fptr);

   return 0;

}

2. Write a C program to read name and marks of n number of students from user and store them in a file. If the file previously exits, add the information of n students.

#include <stdio.h>

int main()

{

   char name[50];

   int marks, i, num;

   printf("Enter number of students: ");

   scanf("%d", &num);

   FILE *fptr;

   fptr = (fopen("C:\\student.txt", "a"));

   if(fptr == NULL)

   {

       printf("Error!");

       exit(1);

   }

   for(i = 0; i < num; ++i)

   {

      printf("For student%d\nEnter name: ", i+1);

      scanf("%s", name);

      printf("Enter marks: ");

      scanf("%d", &marks);

      fprintf(fptr,"\nName: %s \nMarks=%d \n", name, marks);

   }

   fclose(fptr);

   return 0;

}

C program to find number of lines in a file

In this program, we are going to learn how to find total number of lines available in a text file using C program?

This program will open a file and read file’s content character by character and finally return the total number lines in the file. To count the number of lines we will check the available Newline (\n) characters.

File "test.text"

Hello friends, how are you?

This is a sample file to get line numbers from the file.

Program to get/find total number of lines in a file in C

#include <stdio.h>

#define FILENAME "test.txt"

int main()

{

        FILE *fp;

        char ch;

        int linesCount=0;

        

        //open file in read more

        fp=fopen(FILENAME,"r");

        if(fp==NULL)

        {

                printf("File \"%s\" does not exist!!!\n",FILENAME);

                return -1;

        }

        //read character by character and check for new line        

        while((ch=fgetc(fp))!=EOF)

        {

                if(ch=='\n')

                        linesCount++;

        }

        

        //close the file

        fclose(fp);

        

        //print number of lines

        printf("Total number of lines are: %d\n",linesCount);

        

        return 0;        

}

Output

Total number of lines are: 2

C Code Snippet - Read Content of a File using getc() using C Program

/*C - Read Content of a File using getc()

using C Program.*/

#include <stdio.h>

int main(){

        //file nane

        const char *fileName="sample.txt";

        //file pointer

        FILE *fp;

        //to store read character

        char ch;

        

        //open file in read mode

        fp=fopen(fileName,"r");

        if(fp==NULL){

                printf("Error in opening file.\n");

                return -1;

        }

        printf("Content of file\n");

        while((ch=getc(fp))!=EOF){

                printf("%c",ch);

        }

        fclose(fp);

        

        return 0;

}

    Content of file

    This is sample.txt file document.

------------------------------------------------------------------------------------------------------------------

Compile and Link C Program

There are three basic phases occurred when we execute any C program.

Compiling Linking

Preprocessing Phase

A C pre-processor is a program that accepts C code with preprocessing statements and produces a pure form of C code that contains no preprocessing statements (like #include).

Preprocessing

Compilation Phase

The C compiler accepts a preprocessed output file from the preprocessor and produces a special file called an object file. Object file contains machine code generated from the program

Compiling

Linking Phase

The link phase is implemented by the linker. The linker is a process that accepts as input object files and libraries to produce the final executable program.

Linking