Lecture 12
Lecture 12
categorized as:
•Text file
•Binary file
File Operations
•Closing a file
FILE *ptr;
FILE *ptr;
Opening a file
Opening a file is performed using library
function fopen(). The syntax for opening a
file in standard I/O is:
ptr=fopen("fileopen","mode")
For Example:
fopen("E:\\cprogram\
program.txt","w");
/*----------------------------------------------- */
E:\\cprogram\program.txt is the location to
create file. "w" represents the mode for
writing.
/*----------------------------------------------- */
Here, the program.txt file is opened for writing
mode.
Open for append. i.e, Data is If the file does not exists, it
a
added to end of file. will be created.
Open for both reading and If the file does not exist,
r+
writing. fopen() returns NULL.
Open for both reading and If the file does not exists, it
a+
appending. will be created.
Closing a File
#include <stdio.h>
int main()
{ int n; FILE *fptr; fptr=fopen("C:\\
program.txt","w"); if(fptr==NULL)
{ printf("Error!");
exit(1); }
printf("Enter n: ");
scanf("%d",&n);
fprintf(fptr,"%d",n);
fclose(fptr);
return 0;}
This program takes the number from user and
stores in file. After compile and run this
program, we can see a text file program.txt
created in C drive of your computer.
When we open that file, we can see the integer
we entered.
#include <stdio.h>
int main()
{ int n; FILE *fptr;
if(fptr=fopen("C:\\program.txt","r"))==NULL)
{ printf("Error! opening file");
exit(1);
/* Program exits if file pointer returns NULL. */ }
fscanf(fptr,"%d",&n);
printf("Value of n=%d",n);
fclose(fptr);
return 0;}
12
If we have run program above to write in file
successfully, we can get the integer back entered in that
program using this program.
13