Introduction
C Programming
C Advanced
Important C Programs
Modal Box
Tutorials
File Handling
To work with Files pointer variable of FILE type has to be declared like following:
FILE *fp;
The following operations may be performed on a File:
- Create a new file
- Open an existing file
- Close a file
- Read from a given file.
- Write into a file.
Commonly used modes of opening a File;
1 Read Mode: fp = fopen("filename","r")
2 Write Mode: fp = fopen("filename","w"). In this mode, if file does not exists new file is created, and old content is replaced if file exist.
3 Append Mode: fp = fopen("filename","a") In this mode, new content is appended with the old content of the file.
Program to Read the contents of a File and print it Back .
#include <stdio.h> #include <conio.h> void main() { int num; FILE *fp; char ch;
int noc=0;
fp = fopen("test.c","r");
// Full path to open a file as below
//fp = fopen("D:\\TestFolder\\test.txt","r");
if(fp == NULL) { printf("File not exist"); exit(1); } else { ch=fgetc(fp); while(ch!=EOF) { printf("%c", ch); ch=fgetc(fp);
noc++; }
printf("\n no of characters in the file=%d",noc);
} }// end of main
Program to Copy the contents of a File to another File .
#include <stdio.h> #include <conio.h> void main() { int num; FILE *fp, *fp1; char ch; fp = fopen("test.c","r"); fp1 = fopen("writefile.c","w");
if(fp == NULL) { printf("File not exist"); exit(1); } else { ch=fgetc(fp); while(ch!=EOF) { fputc(ch, fp1); ch=fgetc(fp); } } fclose(fp); fclose(fp1); }
Video/ C Introduction
Watch video in full size