Vous êtes sur la page 1sur 19

Introduction to Programming

Engr. Rashid Farid Chishti


chishti@iiu.edu.pk
File Handling in C

International Islamic University H-10, Islamabad, Pakistan


http://www.iiu.edu.pk

What is a File ?

A file is a collection of related data. C treats a file as a series


of bytes. Many files reside on hard disk or usb memory stick;
The declarations for the structures and functions used by the
file functions are stored in the standard include file <stdio.h>
Before doing anything with files, you must put the line:
#include <stdio.h>

At the beginning of your program. The declaration for a file


variable is:
FILE *file-variable; /*comment*/
For example:
#include <stdio.h>
FILE *in_file; /* file containing the input data */

Before a file can be used, it must be opened using the


function fopen. fopen returns a pointer to the file structure
for the file.

What is a File ?

The format for fopen is:


where:
file-variable: is a file variable. A value of NULL is
returned on error.
name: is the actual name of the file (data.txt, temp.dat, etc.).
mode: indicates if the file is to be read or written. mode is
"w" for writing and "r" for reading.
The flag "b" can be added to indicate a binary file.
Omitting the binary flag indicates an ASCII (text) file.
Flags can be combined. So "wb" is used to write a binary
file. The function returns a file handle that will be used in
subsequent I/O operations.
If there is an I/O error, then the value NULL is returned:
file-variable = fopen(name, mode);

Table: File-Type Specifications

mode

Meaning

"rb"

Open an existing binary file for reading only.

"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"

Open an existing binary file for both reading and writing.

"w+b"
or
"wb+"
"a+b"
or
"ab+"

Open a new binary file for both reading and writing. 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 both reading and
appending. A new file will be created if the file with the
specified file-name does not exist.

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 ) ;
}

Reading from a file (1/2)


#include <stdio.h>
#include <iostream>
using namespace std;
int main( ){
FILE * fpt ; /* define a pointer to predefined
structure type FILE */
char c; /* open a new data file for reading only*/
fpt = fopen("sample.txt", "r");
if ( fpt == NULL ){
cout << "cannot open file \n";
system("PAUSE");
exit(0) ;
}

Reading from a file (2/2)


do {
c = fgetc(fpt);
cout << c;
} while (c != EOF) ;
/* close the data file */
fclose ( fpt ) ;
system("PAUSE");
return 0;
}

Reading from a file (1/2)


/* Count chars, spaces, tabs and newlines in a file */
#include "stdio.h"
#include <iostream>
using namespace std;
int main(){
FILE *fp; char ch ;
int Nol = 0;
int Not = 0, Nob = 0, Noc = 0;
fp = fopen ( "main.cpp", "r" ) ;
while (1){
ch = fgetc( fp );
if ( ch == EOF )
break ;
Noc++ ;
if ( ch == ' ' )
Nob++ ;

Reading from a file (2/2)


if ( ch == '\n' )
Nol++ ;
if ( ch == '\t' )
Not++ ;
}
fclose ( fp ) ;
cout << "\nNumber
cout << "\nNumber
cout << "\nNumber
cout << "\nNumber
system("PAUSE");
return 0;
}

of
of
of
of

characters = "<< Noc;


blanks = "<< Nob;
tabs = "<< Not;
lines = "<< Nol ;

A File Copy Program (1/2)


#include <stdio.h>
#include <iostream.h>
using namespace std;
int main(){
FILE *fs, *ft ; char ch ;
fs = fopen ( "main.cpp", "rb" ) ;
if (fs == NULL ){
cout<< "Cannot open source file\n";
system("PAUSE");
exit(0);
}
ft = fopen ( "new.c", "wb" ) ;
if (ft == NULL ){
cout << "Cannot open target file\n";
fclose ( fs ) ;

A File Copy Program (2/2)


system("PAUSE");
exit(0) ;
}
while (1){
ch = fgetc ( fs ) ;
if ( ch == EOF )
break ;
else
fputc ( ch, ft ) ;
}
fclose ( fs ) ;
fclose ( ft ) ;
system("PAUSE");
return 0;
}

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;
}

Writing Records using structures (1/2)


/* Writes records to a file using structure */
#include <stdio.h>
#include <conio.h>
#include <iostream>
using namespace std;
struct item{
int code ;
char name[80] ;
float price ;
};
int main( ){
FILE *fp ;
char another = 'y' ;
struct item t1 ;
fp = fopen ( "shop.txt", "wb" ) ;
if ( fp == NULL ){
cout << "Cannot open file" ;
exit(0) ;

Writing Records using structures (2/2)


while ( another == 'y' ){
cout << "\nEnter item name: "; gets(t1.name);
cout << "Enter item code: "; cin >> t1.code;
cout << "Enter price
: "; cin >> t1.price;
fwrite ( &t1, sizeof ( t1 ), 1, fp ) ;
cout << "\n Add another record (Y/N) " ;
fflush (stdin) ;
fflush (stdout);
another = getch() ;
}
fclose ( fp ) ;
system("PAUSE");
return 0;
}

Reading Records using structures (1/2)


/* Writes records to a file using structure */
#include <stdio.h>
#include <conio.h>
#include <iostream>
using namespace std;
struct item { int code; char name[80]; float price; };
int main( ){
struct item t1 ;
FILE *fp ;
char another = 'y' ;
fp = fopen ( "shop.txt", "rb" ) ;
if ( fp == NULL ){
cout << " Cannot open file " << endl;
exit(0);
} // read 1 item
while ( fread ( &t1, sizeof ( t1 ), 1, fp ) == 1 ){
cout << endl;
cout << "Code : " << t1.code << endl;

Reading Records using structures (2/2)


cout << "Name : " << t1.name << endl;
cout << "price: " << t1.price << endl;
}
fclose ( fp ) ;
system("PAUSE");
return 0;
}

View Records File

Shop.txt

Vous aimerez peut-être aussi