8 Files
8 Files
PROGRAMMING
File Handling in C
Files
or “w” or “w++”)
FILE *filepointer;
• filepointer
– contains all information about file
– Communication link between system and program
• Mode can be
– r open file for reading only
– w open file for writing only
– a open file for appending (adding) data
Modes
• Writing mode
– if file already exists then contents are deleted,
– else new file with specified name created
• Appending mode
– if file already exists then file opened with contents
safe
– else new file created
• Reading mode
– if file already exists then opened with contents safe
– else error occurs.
Modes
loads it into memory and sets up a pointer that points to the last
character in it. If the file doesn’t exist, a new file is created. Returns
p1 = fopen(“data”,”r”);
• This Ensures
– All outstanding information associated with file
flushed out from buffers
– All links to file broken
– Accidental misuse of file prevented
Example:
So, it depends on you if you want to read the file line by line or
character by character.
FILE * filePointer;
FILE *filePointer ;
position */
fseek(fp,m,0); /* move to (m+1)th byte in file */
fseek(fp, -10, 2); /* what is this? */
#include<stdio.h>
int main( )
{
FILE *fp ;
struct emp
{
char name[40] ;
int age ;
float bs ;
};
struct emp e ;
fclose ( fp ) ;
return 0;
}
EXAMPLE:
COPY ONE FILE TO ANOTHER FILE
#include<stdio.h>
int main( )
{
FILE *fp,*fp2 ;
struct emp
{
char name[40] ;
int age ;
float bs ;
};
struct emp e ;
fclose (fp) ;
fclose (fp2) ;
return 0;
}
Example
Program to read/write using getc/putc
#include <stdio.h>
main()
{ FILE *fp1;
char c;
f1= fopen(“INPUT”, “w”); /* open file for writing */
fclose(f1); /* close
INPUT */
f1=fopen(“INPUT”, “r”); /* reopen file */