Download as pdf or txt
Download as pdf or txt
You are on page 1of 16

Advanced Programming Languages: File Handling 

 
FILE HANDLING 
 
Source Code:  before: 
   
#include <iostream> 
using namespace std; 
int main() 

  FILE *fp; 
  fp=fopen("d:\myfile\sample.txt","w");
  fclose(fp); 
  system("pause>0"); 
  return 0;   
}   
after: 

 
 
 
FILE *fp; 
 
File pointer points to a structure that contains about the file, such as the location of a buffer, 
the character position in the buffer, whether the file is being read or written, and whether 
errors or end of file have occurred. 
 
fp=fopen("d:\sample.txt","w"); 
 
fopen is a library function used before reading and writing a file. 
    
FILE *fopen(char *name, char *mode) 
name – is a character string containing the name of the file. 
mode – a character string, which indicates how one intends to use the file. 
    “r”  open text file for reading 
    “w”  write text file for writing; discard previous contents if any 
    “a”  append; open or create text file for writing at end of file 
    “r+”  open text file for update (i.e. reading and writing) 
    “w+”  create text file for update, discard previous contents if any 
    “a+”  append; open or create text file for update, writing at end 
Update mode permits reading and writing the same file 

RMDA  Page 1 
 
Advanced Programming Languages: File Handling 
 
If a file that does not exist is opened for writing or appending, it is created if possible. Opening an 
existing file for writing cause the old contents to be discarded, while are opening for appending 
preserves them. Trying to read a file that does not exist is an error, and there may be other causes of 
error as well, like trying to read a file when you don’t have permission. If there is any error, fopen will 
return NULL. 
 
fclose is the inverse of fopen, it breaks the connections between the file pointer and the 
external name that was established by fopen, freeing the file pointer for another file. 
 
  int fclose(FILE *fp);     
 
Writing to a file 
 
Source Code: 
 
#include <iostream> 
using namespace std; 
int main() 

  FILE *fp; 
  fp=fopen("e:\\myfiles\\sample.txt","w"); 
   
  //Check permission if you can write a file 
  if(!fp) 
  { 
    cout << "Cannot open file.\n"; 
    system("pause"); 
    exit(1); 
  } 
 
  //Prints the character ASCII value from 65 to 90 (A‐Z) to a file 
  for(int i=65;i<91;i++) 
    fputc(i,fp); 
 
  fclose(fp); 
  return 0; 

 
Output: 
Case 1 

 
 
Case 2 

RMDA  Page 2 
 
Advanced Programming Languages: File Handling 
 
fputc write the character c to the file and returns the character written, or EOF if an error occurs. 
  int fputc(int c, FILE *fp); 
 
see also putc 
 
Reading from a file 
 
Source Code: 
 
#include <iostream> 
using namespace std; 
int main() 

  FILE *fp; 
  fp=fopen("d:\\myfiles\\sample.txt","r"); 
   
  if(!fp) 
  { 
    cout << "Cannot open file.\n"; 
    system("pause"); 
    exit(1); 
  } 
 
  //Get each character from the file and prints to the screen 
  //until it reach the end of file (EOF) 
  char c; 
  while((c = fgetc(fp))!=EOF) 
    cout << c; 
   
  fclose(fp); 
  system("pause > 0"); 
  return 0; 

 
Output: 
 
 
 
 
fgetc returns the next character from the stream referred to by file pointer (fp); it returns EOF 
for end of file or error. 
  int fgetc(FILE *fp); 
 
see also getc 
 
 

RMDA  Page 3 
 
Advanced Programming Languages: File Handling 
 
Appending to a file 
 
 
Source Code: 
 
#include <iostream> 
using namespace std; 
int main() 

  FILE *fp; 
  fp=fopen("d:\\myfiles\\sample.txt","a"); 
   
  if(!fp) 
  { 
    cout << "Cannot open file.\n"; 
    system("pause"); 
    exit(1); 
  } 
  fputc('\n',fp); 
  //Prints and append character ASCII value from 97‐122 (a‐z) to a file 
  for(int i=97;i<123;i++) 
    fputc(i,fp); 
 
  fclose(fp); 
  return 0; 

 
before: 
 

 
 
after: 
 

 
 
 
 
 
 
 
 
 
 

RMDA  Page 4 
 
Advanced Programming Languages: File Handling 
 
File Line Input and Output 
 
Writing 
 
 
Source Code: 
 
#include <iostream> 
using namespace std; 
int main() 

  FILE *fp; 
  fp=fopen("d:\\myfiles\\sample2.txt","w"); 
   
  if(!fp) 
  { 
    cout << "Cannot open file.\n"; 
    system("pause"); 
    exit(1); 
  } 
 
  fputs("sample string 1\n",fp); 
  fputs("sample string 2",fp); 
 
  fclose(fp); 
  return 0; 

 
Output: 
 

 
 
 
fputs writes a string (which need not contain a newline) to a file it returns EOF if an error occurs, and 
non negative otherwise. 
 
int fputs(char *line, FILE *fp) 
 
 
 
 
 
 
 

RMDA  Page 5 
 
Advanced Programming Languages: File Handling 
 
Reading 
 
Source Code: 
 
#include <iostream> 
using namespace std; 
int main() 

  FILE *fp; 
  char buff[1000]; 
  fp=fopen("d:\\myfiles\\sample2.txt","r"); 
  if(!fp) 
  { 
    cout << "Cannot open file.\n"; 
    system("pause"); 
    exit(1); 
  } 
   
  while(fgets(buff,1000,fp)!=NULL) 
    cout << buff; 
 
  fclose(fp); 
  system("pause>0"); 
  return 0; 

 
Output: 
 

 
 
 
fgets reads the next input line (including the newline) from file pointer (fp)  into the character array line. 
The resulting line is terminated by ‘\0’. Normally fgets return line; on end of file (EOF) or error it returns 
NULL. 
  char *fgets(char *line, int maxline, FILE *fp) 
 
The library functions gets and puts are similar to fgets and fputs, but operate on stdin and stdout. 
Confusingly, gets deletes the terminating ‘\n’, and puts adds it. 
 
 
 
 
 
 
 
 
 

RMDA  Page 6 
 
Advanced Programming Languages: File Handling 
 
Formatted Input and Output Files 
 
Writing 
 
Source Code: 
 
#include <iostream> 
using namespace std; 
int main() 

  FILE *fp; 
  fp=fopen("d:\\myfiles\\sample3.txt","w"); 
   
  if(!fp) 
  { 
    cout << "Cannot open file.\n"; 
    system("pause"); 
    exit(1); 
  } 
 
  for(int x=1;x<=10;x++) 
  { 
    for(int y=1;y<=10;y++) 
      fprintf(fp,"%5d",x*y); 
    fputc('\n',fp); 
  } 
 
  fclose(fp); 
  return 0; 

 
Output: 
 

 
 
 
 
fprintf converts and writes output to stream under the control of format. The return value is the 
number of characters written, or negative if an error occurred. 
 
  int fprintf(FILE *stream, const char *format, …) 
 

RMDA  Page 7 
 
Advanced Programming Languages: File Handling 
 
Reading 
Source File: 
(sample4.txt) 

 
 
Source Code: 
#include <iostream> 
using namespace std; 
int main() 

  FILE *fp; 
  fp=fopen("d:\\myfiles\\sample4.txt","r"); 
   
  if(!fp) 
  { 
    cout << "Cannot open file.\n"; 
    system("pause"); 
    exit(1); 
  } 
 
  int id; 
  char name[20]; 
  float price; 
  fscanf(fp,"%d%s%f",&id,&name,&price); 
  cout << "Item (Data from file)\n"; 
  cout << "ID: " << id << endl; 
  cout << "Name: " << name << endl; 
  cout << "Price: " << price << endl; 
   
  fclose(fp); 
  system("pause > 0"); 
  return 0; 

 
Output: 
 

 
 
 
fscanf reads from stream under control of format, and assign converted values through subsequent 
arguments, each of which must be a pointer. fscanf returns EOF if the end of file or error occurs before 
any conversion; otherwise it returns the number of input items converted and assigned. 
 
  int fscanf(FILE *stream, const char *format, …) 
 

RMDA  Page 8 
 
Advanced Programming Languages: File Handling 
 
Stream 
  Is a flow of characters (or other kind of data). If the flow is into your program, the stream is 
called an input stream. If the flow is out of your program, the stream is called an output stream. If the 
input streams flows from the keyboard, then your program will take input from the keyboard. If the 
input stream flows from a file, then your program will take its input from that file. 
 
Writing to a file 
  You create a stream object and use the ostream methods, such as << insertion operator or 
write( ).  
 
• Create an ofstream object to manage the ouput stream. 
• Associate that object with a particular file. 
• Use the object the same way you would use cout; the only difference is that output goes to the 
file instead of to the screen. 
 
ofstream fout;    // create an ofstream object named fout 
fout.open(“sample.txt”);  // associate fout with cookies 
 
or simply 
 
ofstream fout(“sample.txt”);  // create fout object and associate with cookies 
 
Opening a file for output this way creates a new file if there is no file of that name. If a file by that name 
is exists prior to opening it for output, the act of opening  it truncates it so that output starts with a 
clean file. 
 
Source Code (Creatinga file): 
#include <fstream> 
using std::ofstream; 
int main() 

  ofstream fout; 
  fout.open("d:\\stream\\sample.txt"); 
  fout.close(); 
  return 0; 

 
 
 
 
 
 
 

RMDA  Page 9 
 
Advanced Programming Languages: File Handling 
 
Before 

 
After 

 
 
Source Code (writing to a file)  Output: 
#include <fstream> 
using std::ofstream; 
int main() 

  ofstream fout; 
  fout.open("d:\\stream\\sample1.txt"); 
  fout << "Juan Dela Cruz\n"; 
  fout << " BSCS\n";   
  fout << " 255‐1234"; 
  fout.close(); 
  return 0; 

 
Reading from a file 
  You create a stream object and use the istream methods, such as the >> extraction operator or 
get( ). 
 
• Create an ifstream object to manage the input stream.  
• Associate that object with a particular file. 
• Use the object the same way you would use cin. 
 
ifstream fin; 
fin.open(“sample.txt”); 
 
or simply 
 
ifstream fin(“sample.txt”); 
 
 

RMDA  Page 10 
 
Advanced Programming Languages: File Handling 
 
fstream 
ifstream class for file input 
ofstream  class for file output 
 
Source Code (reading from a file)  Output 
#include <iostream> 
#include <fstream> 
using namespace std; 
int main() 
{   
  ifstream fin; 
  fin.open("d:\\stream\\sample1.txt");
   
  char name[30]; 
  char course[10]; 
  char cn[15]; 
   
  fin.getline(name,30); 
  fin.getline(course,10); 
  fin.getline(cn,15); 
  cout << "Display Record\n"; 
  cout << "Name: " << name << endl; 
  cout << "Course: " << course << endl; 
  cout << "Contact No.: " << cn << endl; 
   
  fin.close(); 
 
  system("pause > 0"); 
  return 0; 

 
 
Source Code 
#include <iostream> 
#include <fstream> 
using namespace std; 
int main(int argc, char *argv[]) 

  if(argc==1) 
  { 
    cerr << "Usage: " << argv[0] << "filename[s]\n"; 
    exit(1); 
  } 
  ifstream fin; 
  long count; 
  long total = 0; 
  char ch; 
  for(int i=1;i<argc;i++) 
  { 
    fin.open(argv[i]); 
    count = 0; 
    while(fin.get(ch)) 
      count++; 

RMDA  Page 11 
 
Advanced Programming Languages: File Handling 
 
    cout << count << " characters in " << argv[i] << "\n"; 
    total+=count; 
    fin.clear(); 
    fin.close(); 
  } 
  cout << total << " characters in all files\n"; 
  return 0; 

 
Create a text file 

 
and 

 
 
Go to the directory where your executable file is located 

 
 
To run the program (run in command line) 

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

RMDA  Page 12 
 
Advanced Programming Languages: File Handling 
 
The C++ file stream classes inherit a stream‐state member from the ios_base class. It stores information 
reflecting the stream status: all as well, end‐of‐file has been reached, I/O operation failed, and so on. 
 
is_open( ) 
  a method used to check if a file has been opened 
 
Source Code: 
#include <iostream> 
#include <fstream> 
using namespace std; 
int main()   

  ifstream fin; 
  char fn[50]; 
  char yn; 
  do{ 
    system("cls"); 
    cout << "Open a file: "; 
    cin >> fn; 
    fin.open(fn); 
    if(!fin.is_open()) 
    { 
      cout << "Couldn't open the file " << fn << endl; 
      fin.clear(); //reset failbit 
    } 
    else 
    { 
      cout << "File " << fn << " is now opened" << endl; 
    } 
    cout << "Enter X to exit: "; 
    cin >> yn; 
    fin.close(); 
  }while(yn!='X' && yn!='x');   
  return 0; 

 
 
Output 
Consider you have happy.txt file 

 
 
 
Case 1: 

 
 

RMDA  Page 13 
 
Advanced Programming Languages: File Handling 
 
Case 2: 

 
 
 
 
File Modes 
  Describes how a file is to be used : read it, write to it, and append it. 
 
Syntax 
  //contructor with mode argument 
  ifstream ("myfile", mode1); 
  //open with mode arguments 
  ofstream fout(); 
  fout.open("yourfile", mode2); 
 
Table File Mode Constants 
ios_base::in  Open file for reading 
ios_base::out  Open file for writing 
ios_base::ate  Seek to end‐of‐file upon opening file 
ios_base::app  Append to end‐of‐file 
ios_base::trunc  Truncate file if exists 
ios_base::binary  Binary file 
 
Default values 
  ifstream open( )   ‐ios_base::in 
  ofstream open( )  ‐ ios_base::out | ios_base::trunc 
 
Appending to a file 
Source Code: 
#include <iostream> 
#include <fstream> 
using namespace std; 
 
int main() 

  ofstream fout("d:\\stream\\happy.txt", ios_base::out | ios_base::app); 
  fout << "\nAdditional Statement"; 
  fout.close(); 
  return 0; 

 
 
 
 
 
 
 

RMDA  Page 14 
 
Advanced Programming Languages: File Handling 
 
Output: 
Before: 

 
After: 

 
Binary Text File 
  Using a binary file mode causes a program to transfer data from memory to a file, or vice versa, 
without any hidden translation taking place.  
 
Source Code: 
#include <iostream> 
#include <fstream> 
using namespace std; 
 
struct Planet{ 
  char name[20]; 
  double population; 
  double gravity; 
}; 
 
int main() 

  Planet pl={"Earth",7000000000,9.81}; 
  ofstream fout("d:\\stream\\planet.txt",ios_base::app | ios_base::binary ); 
  fout.write((char *) &pl, sizeof pl); 
  fout.close(); 
  return 0; 

 
Output: 

 
 
 
 
 
 
 
 
 
 

RMDA  Page 15 
 
Advanced Programming Languages: File Handling 
 
 
 
Source Code: 
#include <iostream> 
#include <fstream> 
using namespace std; 
 
struct Planet{ 
  char name[20]; 
  double population; 
  double gravity; 
}; 
 
int main() 

   
  Planet pl; 
  ifstream fin("d:\\stream\\planet.txt",ios_base::binary); 
  fin.read((char *) &pl, sizeof pl); 
  cout << pl.name << endl; 
  cout << pl.population << endl; 
  cout << pl.gravity << endl; 
  system("pause>0"); 
  return 0; 

 
Output: 

 
 
 
 
 
 
 

RMDA  Page 16 
 

You might also like