File Handling in C
File Handling in C
What is a File ?
What is a File ?
mode
Meaning
"rb"
"wb"
"ab"
Open a new binary file for writing only. If a file with the
specified file-name currently exists, it will be destroyed and
a new file created in its place.
Open an existing binary file for appending (i.e., for adding
new information at the end of the file). A new file will be
created if the file with the specified file-name does not
exist.
"r+b"
"w+b"
or
"wb+"
"a+b"
or
"ab+"
What is a File ?
FILE *in_file;
/* File to read */
in_file = fopen("input.txt","r"); /* Open the input
file */
if (in_file == NULL) { /* Test for error */
fprintf(stderr,"Error: Unable to input file
'input.txt'\n");
exit (8);
}
The function fclose will close the file. The format of fclose is:
status = fclose(file-variable);
OR
fclose(file-variable);
The variable status is zero if the fclose was successful or
nonzero for an error.
If you don't care about the status, the second form closes
the file and discards the return value.
Writing to A file
#include <stdio.h>
#include <ctype.h>
int main( ){
FILE * fpt ; /* define a pointer to predefined
structure type FILE */
char c;
/* open a new data file for writingo nly */
fpt = fopen("sample.txt", "w");
/* read each character and write its uppercase
equivalent to the data file */
do
putc(toupper(c = getchar()), fpt ) ;
while (c != '\n') ;
/* close the data file */
fclose ( fpt ) ;
}
of
of
of
of
Writing a string
// Receives strings from keyboard and writes to file
#include <stdio.h>
#include <iostream>
using namespace std;
int main( ){
FILE *fp ;
char s[80] ;
fp = fopen ( "POEM.TXT", "w" ) ;
if ( fp == NULL ){
cout << "Cannot open file"; exit(0);
}
cout << "\nEnter a few lines of text:\n" ) ;
while ( strlen ( gets ( s ) ) > 0 ){
fputs ( s, fp ) ; fputs ( "\n", fp ) ;
}
fclose ( fp ) ; system("PAUSE"); return 0;
}
Reading a string
// Reads strings from the file and displays on screen
#include <stdio.h>
#include <iostream>
using namespace std;
int main( ){
FILE *fp ; char s[80] ;
fp = fopen ( "POEM.TXT", "r" ) ;
if ( fp == NULL ){
cout << "Cannot open file" << endl; exit (0) ;
}
while ( fgets ( s, 79, fp ) != NULL )
cout << s ;
fclose ( fp ) ;
system("PAUSE"); return 0;
}
Shop.txt