fstream
From Wikipedia, the free encyclopedia
This article or section contains instructions, advice, or how-to content. The purpose of Wikipedia is to present facts, not to teach subject matter. Please help improve this article by removing or rewriting the how-to content, which may qualify for a move to http://www.wikihow.com/ or http://howto.wikia.com/. This article has been tagged since April 2008. |
C++ Standard Library |
---|
ios |
iostream |
iomanip |
map |
fstream |
C Standard Library |
cassert |
cctype |
cerrno |
cfloat |
cmath |
cstdio |
cstdlib |
ctime |
fstream is a c++ library that enables reading and writing to files either in text or in binary.
Contents |
[edit] Text Files in fstream
For text files, a common method includes using the <<
and >>
syntax that is followed with cout
in the iostream library. The following example creates a file called 'file.txt' and puts the text 'Hello World' into it.
#include <fstream> int main() { ofstream file; file.open("file.txt"); file << "Hello world!\n"; file.close(); }
[edit] Binary Files in fstream
Reading from and writing to binary files uses the following functions:
fstream::write(char *buff,int size); fstream::read(char *buff, int size);
where buff is the buffer to write to or read from, and size is an integer number of bytes. www.cplusplus.com explains that these functions are necessary as the use of "the extraction and insertion operators (<< and >>) and functions like getline is not efficient, since we do not need to format any data, and data may not use the separation codes used by text files to separate elements (like space, newline, etc...)."
The following example creates a file called 'file.bin', creates a 100 element buffer, and writes 20 bytes from the buffer into the file.
#include <fstream.h> int main() { char buffer[100]; ofstream file; file.open("file.bin", ios::out | ios::binary); //opens the file for binary output file.write(buffer, 20); //this writes 20 bytes from buffer to file.bin file.close(); }
Reading from a binary file is very similar. The following example opens the file called 'file.bin', creates a 100 element buffer, and reads 20 bytes from the file into the buffer.
#include <fstream.h> int main() { char buffer[100]; ifstream file; file.open("file.bin", ios::in | ios::binary); //opens the file for binary input file.read(buffer, 20); //this reads 20 bytes from file.bin to the buffer file.close(); }
Note: it is a good idea to use the c++ operator sizeof to indicate how many bytes to write to the file. The following would write 4 bytes from the buffer to the file, as the size of the type int is 4 bytes.
file.write(buffer, sizeof(int));
Here comes the program that will update the binary file.
- include<iostream.h>
- include<fstream.h>
- include<conio.h>
class inventory {
char *name; int code; float cost;
public:
inventory() { name=new char[20];} void getData() { cout<<"Enter name , code and cost\n"; cin>>name>>code>>cost;} int getCode() {return code;} void disData() { cout<< "Name Code Cost\n"; cout<<name<<" "<<code<<" "<<cost<<endl; } }I[5],S; int main() { fstream file; file.open("stock.txt",ios::out); clrscr(); for(int i=0;i<3;i++) { I[i].getData(); file.write((char*)&I[i],sizeof(inventory)); } file.close(); clrscr(); file.open("stock.txt",ios::in); cout<<"\n Stock items are...\n\n"; file.read((char*)&S,sizeof(inventory)); while(file) { S.disData(); file.read((char*)&S,sizeof(inventory)); }
cout<<"To update product Enter the Code number\n"; int cc; cin>>cc; file.close();
file.open("stock.txt",ios::out|ios::in|ios::app); file.read((char*)&S,sizeof(inventory)); while(file) { if(cc==S.getCode()) {
S.getData(); int y=file.tellg(); file.seekp(y,ios::beg); file.write((char*)&S,sizeof(inventory)); cout<<"Bytes"<<" "<<file.tellp()/sizeof(inventory); break; } else { file.read((char*)&S,sizeof(inventory)); } } file.close(); cout<<"\n Stock items are...\n\n"; file.open("stock.txt",ios::in); file.read((char*)&S,sizeof(inventory)); while(file) { S.disData(); file.read((char*)&S,sizeof(inventory)); } }
[edit] initializing files
When initializing a file, there are several modes you can choose, depending on what operation or function you are using the file for. The different modes you can use are as follows:
Mode | What it does |
---|---|
ios::in |
If the file does not exist, a new empty file is created. If the file exists, it is opened and made available for processing as input. |
ios::out |
If the file does not exist, a new empty file is created, ready to be written to. If the file exists, it is opened, and the previous content in it is deleted, and is then made ready to be written to. |
ios::trunc |
If the file does not exist, a new empty file is created. If the file exists, its content is deleted and it is treated as a new file. |
ios::app |
If the file does not exist, a new empty file is created for writing to. If the file exists, it is opened for writing, and whatever is written to the file will be written at the end of the existing file, not overwriting any existing data. |
ios::ate |
If the file does not exist, a new empty file is created and data is written to it, and afterwards to the end of the file. If the file exists, data will be written at the current position if there is data in the existing file. |
ios::binary |
Opens the file as a binary file, for either input or output. |
The following is a snippet of code that shows the function of these modes.
#include <fstream> int main() { ofstream ofile; ofile.open("ex.txt", ios::out); //opens file as output int x=1; ofile<<x; ofile.close(); //ex.txt is now "1" ifstream ifile; ifile.open("ex.txt",ios::in); //opens file as input int a; ifile>>a;//a now equals 1 a=2; ifile.close(); ofile.open("ex.txt", ios::out|ios::trunc); //opens file as output //ex.txt is now empty due to ios::trunc ofile<<x;//write 1 to file //ex.txt is now "1" ofile.close(); ofile.open("ex.txt", ios::out|ios::app); //open file as output ofile<<a;//write 2 to file //ex.txt is now "12" ofile.close(); ofile.open("ex.txt", ios::in|ios::out|ios::ate); //open file as output ofile<<x;//write 1 to file //ex.txt is now "121" ofile.close(); }
-
- NOTE: for ios::ate, simply using this line of code: "ofile.open("ex.txt",ios::out|ios::ate);" will result in the file being overwritten as if ios::ate was not included in the function. Adding ios::in will enable this to function as described in the above table.
[edit] Member functions
What follows is an incomplete list of functions in iostream
library:
Name | Description |
---|---|
(constructor) |
Construct an object and optionally open a file |
rdbuf |
Get the filebuf object associated with the stream. |
is_open |
Check if a file has been opened. |
open |
Open a file. |
close |
Close an open file. |
members inherited from istream: | |
operator>> |
Performs a formatted input operation (extraction) |
gcount |
Get number of characters extracted by last unformatted input operation |
get |
Extract unformatted data from stream |
getline |
Get a line from stream |
ignore |
Extract and discard characters |
peek |
Peek next character |
read |
Read a block of data |
readsome |
Read a block of data |
putback |
Put the last character back to stream |
unget |
Make last character got from stream available again |
tellg |
Get position of the get pointer |
seekg |
Set position of the get pointer |
sync |
Synchronize stream's buffer with source of characters |
members inherited from ostream: | |
operator<< |
Perform a formatted output operation (insertion). |
flush |
Flush buffer. |
put |
Put a single character into output stream. |
seekp |
Set position of put pointer. |
tellp |
Get position of put pointer. |
write |
Write a sequence of characters. |
members inherited from ios: | |
operator void * |
Convert stream to pointer. |
operator ! |
evaluate stream object. |
bad |
Check if an unrecoverable error has occurred. |
clear |
Set control states. |
copyfmt |
Copy formatting information. |
eof |
Check if End-Of-File has been reached. |
exceptions |
Get/set the exception mask. |
fail |
Check if failure has occurred. |
fill |
Get/set the fill character. |
good |
Check if stream is good for i/o operations. |
imbue |
Imbue locale. |
narrow |
Narrow character. |
rdbuf |
Get/set the associated streambuf object. |
rdstate |
Get control state. |
setstate |
Set control state. |
tie |
Get/set the tied stream. |
widen |
Widen character. |
members inherited from ios_base: | |
flags |
Get/set format flags. |
getloc |
Get current locale. |
imbue |
Imbue locale. |
iword |
Get reference to a long element of the internal extensible array. |
precision |
Get/set floating-point decimal presision. |
pword |
Get reference to a void* element of the internal extensible array. |
register_callback |
Register event callback function. |
setf |
Set some format flags. |
sync_with_stdio |
Activates / Deactivates synchronization with cstdio functions. [static ] |
unsetf |
Clear format flag. |
width |
Get/set field width. |
xalloc |
Return a new index for the internal extensible array. [static ] |
See also ifstream, which is the C++ standard library class that enables input of data from files.