0% found this document useful (0 votes)
180 views7 pages

File I and Streams

Uploaded by

Gaby Mbugua
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
180 views7 pages

File I and Streams

Uploaded by

Gaby Mbugua
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 7

File I/O With C++ fstream

Intro

File handling is as simple as writing in a book, much easier to modify and


find. It's so simple people get confused with it :-). Welcome to the world of file handling.

We will use the c++ fstream classes to do our file handling. So, what is a file? A file is just a
bunch of bytes stored on a hardisk. Some have a specific structure others dont. Files are used to
save info so that it can be retrived later for use. [I dont think you will want to save 100 people's
address in memory will you].

Types of Files
Actually there are only two. Text files and binary files.
In text files data is stored as readable chars and binary file are in machine language. So if you
output abc123 to a text file you will see abc123 but in a binary file you may see only a bunch of
black blocks if you use notepad. The binary files are smaller in size.

fstream.h
fstream.h provides simultaneous input and output through ifstream, ofstream and fstream.
ifstream - open the file for input
ofstream - open the file for output
fstream - open the file for input/output/both

Writing to a file
Relatively very simple.

Steps:
Declare an ofstream var.
Open a file with it.
Write to the file (there are a couple of ways.)

Gabriel © 2015 Page 1


Close it.

Eg Program 1.1
#include <fstream.h>

void main
{
ofstream file;

file.open("file.txt"); //open a file

file<<"Hello file\n"<<75; //write to it

file.close(); //close it
}

Methods for Writing to a file


The fstream class is derived from the iostream classes, so you can use ofstream variables exactly
how you use cout. So you can use the insertion (<<) operator and the put().
Usages:

file<<"string\n";
file.put('c');

Reading from a file


Almost the same.
Declare an ifstream var.
Open a file with it.
Read from the file(there are a couple of ways.)
Close it.

Gabriel © 2015 Page 2


Eg Program 1.2
#include <fstream.h>

void main
{
ifstream file;
char output[100];
int x;

file.open("file.txt"); //open a file

file>>output; //write to it
cout<<output; //result = Hello file
file>>x;
cout<<x; //result = 75

file.close(); //close it
}

Methods for Reading a file


The fstream class is derived from the iostream classes, so you can use fstream variables how you
use cin.So you can use the extraction (<<) operator and the put().
Usages:

file>>char *; //ie an array


file>>char; //single char
file.get(char); //single char
file.get(char *,int); //read a string
file.getline(char *,int sz);
file.getline(char *,int sz,char eol);

Gabriel © 2015 Page 3


**Notes:***

The file handles can be used like:


ofstream file("fl.txt");
ifstream file("fl.txt");

You will use the constructor for opening a file.I would not recommend using this not because it
works less well or anything but in most cases it will improve code clarity and prevent errors
when you are handling multiple files. If a file handle is used more than once without calling a
close() in between them there will be errors. This is just provided for info sake if you need to use
it in a hurry or in something small.

Never ever declare a fstream variable globally. It is a bad habit. If you forget to close it next time
you run the program it will show access errors to the C: drive (or which ever drive you use) and
you will have to restart the computer. Declare them within funtions or classes and close them
when their use is over.

If you are doing databases or any file handling for that matter never put any file i/o into classes.
It will simply complicate debugging and you may also open a single file multiple times with
difffrent objects at the same time. This is definitely not what we want. Classes are only to be
used when you have to minimal file i/o but still I recommend you use normal funtions.

ifstream stands for input stream and can only be used for input.
ofstream stands for output stream and can only be used for output.
Any variable declared with ifstream,ofstream or fstream is called a file handle.

That wraps up the simple very stuff. You will not use them much unless you are working with
text files or in a small project. Now we will move on to fstream which is more flexible and will
be most used. It's easy if you look at it logically.

Dynamic file access

Gabriel © 2015 Page 4


The file streams we discussed have a limitation, they can only do input or output at a time.
fstream provides us with a way to read, write randomly without having to close and reopen the
file. It has great flexibility involving a bit more work with returns being ten fold. Hey, you cant
have everything for free (what fun would it be if everything was handed to you).

Lets look at how a file can be opened with fstream.

Program Example 1.3


void main()
{
fstream file;

file.open("file.ext",iso::in|ios::out)

//do an input or output here

file.close();
}

Notice anything new? The ios::--- are attributes which define how a file should be opened.
List of Attributes
ios::in open file for reading
ios::out open file for writing
ios::app open for writing,add to end of file(append).
ios::binary Binary file
ios::nocreate do not create the file,open only if it exists
ios::noreplace open and create a new file if the specified file does not exist
ios::trunc open a file and empty it.(Boom, all the data is gone,if any)
ios::ate goes to end of file instead of the begining

Notes

Gabriel © 2015 Page 5


The default mode is text mode when a file is opened
By default if a file does not exist,a new one is created
Multiple attributes can be specified at a time seperated by ...|...|...
All attributes start with an ios:: (as if you dint notice it,but still let me hammer it)
These attributes can be used with ifstream and ofstream but of course ios::in wont work with
ofstream and similarly ios::out wont .............
File byte location start from zero (like in arrays)
Now we know how to open a file with fstream. Cool, now come read and write.
Reading and Writing with fstream
The two functions are exactly similar in usage and simple to understand
file.write(char *,int); //for writing
file.read(char *,int); //for reading (gee...:D)

Until now we have only been able to use strings and ints to write/read. Most databases will want
to store data in structures or classes. If we had to write a seperate function to split and write each
member, brrr horrors. C++ goes to be very nice and provides us with a way to write entire
classes or structures with little work
struct x
{
int i;
char a;
char s[10];
}data;

file.write((char*)&data,sizeof(x));
file.read((char*)&data,sizeof(x));

Hold on, what the heck is the char * thingy???.

Gabriel © 2015 Page 6


That's called typecasting. Quite an interesting subject actually. It means converting one data type
to another. Here it is converting struct x into a char pointer and it's address is passed to the
funtion. If anybody wants to know more, well tell!

The rest is simple. You pass the size of the structure which can be found out by using sizeof();

Eg:
cout<<"\nInt:"<<sizeof(int);
cout<<"\nFloat:"<<sizeof(float);
cout<<"\nChar:"<<sizeof(char);

Gabriel © 2015 Page 7

You might also like