
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Append Mode Operation of Files in C Language
File is collection of records or is a place on hard disk, where data is stored permanently.
Need of files
Entire data is lost when a program terminates.
Storing in a file preserves the data even if, the program terminates.
If you want to enter a large amount of data, normally it takes a lot of time to enter them all.
We can easily access the content of files by using few commands.
You can easily move your data from one computer to another without changes.
By using C commands, we can access the files in different ways.
Operations on files
The operations on files in C programming language are as follows −
- Naming the file
- Opening the file
- Reading from the file
- Writing into the file
- Closing the file
Syntax
The syntax for declaring a file pointer is as follows −
FILE *File pointer;
For example, FILE * fptr;
The syntax for naming and opening a file pointer is as follows −
File pointer = fopen ("File name", "mode");
For example, to append mode of opening a file, use the syntax given below −
FILE *fp; fp =fopen ("sample.txt", "a");
If the file doesn’t exist, then, a new file will be created.
If the file exists, the current content will be added to the old content.
Program
Following is the C program for opening a file in append mode and counting number of lines present in a file −
#include<stdio.h> #define FILENAME "Employee Details.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!!!
",FILENAME); return -1; } //read character by character and check for new line while((ch=getc(fp))!=EOF){ if(ch=='
') linesCount++; } //close the file fclose(fp); //print number of lines printf("Total number of before adding lines are: %d
",linesCount); fp=fopen(FILENAME,"a"); //open fine in append mode while((ch = getchar())!=EOF){ putc(ch,fp); } fclose(fp); fp=fopen(FILENAME,"r"); if(fp==NULL){ printf("File \"%s\" does not exist!!!
",FILENAME); return -1; } //read character by character and check for new line while((ch=getc(fp))!=EOF){ if(ch=='
') linesCount++; } //close the file fclose(fp); //print number of lines printf("Total number of after adding lines are: %d
",linesCount); return 0; }
Output
When the above program is executed, it produces the following result −
Total number of lines before adding lines are: 3 WELCOME to Tutorials Its C Programming Language ^Z Total number of after adding lines are: 8