File Handling
File Handling
Pratik Narang
BITS Pilani
Pilani Campus
BITS Pilani
Pilani Campus
File handling in C
Why files?
• Preserve the output
• Easy analysis
• Large data (input or output)
Working with files
• First, establish a buffer area.
• Here the information will be stored temporarily while
being transferred between the computer’s memory and
the file.
• It allows information to be read from or written to the file
more rapidly.
• FILE *fp;
• FILE – establishes the buffer area
• fp – pointer variable indicating the beginning of buffer area
Opening/closing a file
• A file must be opened before it is processed.
• It associates the file name with the buffer area (the file
pointer).
• It also specifies how the file will be utilized
• Read-only
• Write-only
• Read/write
• fp = fopen(file-name, mode);
• fclose(fp);
File modes
If FILE-
Mode Meaning
Exists Doesn’t exist
r Reading – NULL
w Writing Over write on Existing Create New File
a Append – Create New File
New data is written at
r+ Reading + Writing the beginning, Create New File
overwriting existing data
w+ Reading + Writing Over write on Existing Create New File
New data is appended
a+ Reading + Appending Create New File
at the end of file
Reading from / writing to files
• fscanf()
• Declaration: int fscanf(FILE *fp, const char *format, …)
• fprintf()
• Declaration: int fprintf(FILE *fp, const char *format, …)
• fgetc ()
• Declaration: int fgetc(FILE *fp)
• fputc()
• Declaration: int fputc(int char, FILE *fp)
What does this code do?
int main()
{
char c[1000];
scanf("%[^\n]", c);
printf("\n***%s***\n", c);
return 0;
}
What does this code do?
int main()
{
char c[1000];
FILE *fp;
fp = fopen(“one.txt”, “r”);
fscanf(fp, "%[^\n]", c);
printf("\n***%s***\n", c);
fclose(fp);
return 0;
}
What does this code do?
int main ()
{
return 0;
}
What does this code do?
int main ()
{
FILE* fp;
fp = fopen(“1.txt”, “w”);
for(int i = 0; i < 10;i++)
fprintf(fp,“Line %d\n",i+1);
fclose(fp);
return 0;
}
Cope file f1.txt to f2.txt
FILE *fp1 = fopen ("f1.txt", "r");
FILE *fp2 = fopen ("f2.txt", "w");
int ch;
while ((ch = getc(fp1)) != EOF)
putc(ch, fp2);
/* as long as some content is yet to be read
in the source file, continue; else don’t */
fclose(fp1);
fclose(fp2);
Double space a file
FILE *fp1 = fopen ("f1.txt", "r");
FILE *fp2 = fopen ("f2.txt", "w");
int ch;
while ((ch = getc(fp1)) != EOF) {
putc(ch, fp2);
if (ch == '\n') putc(ch, fp2);
}
fclose(fp1);
fclose(fp2);