Classes For File Stream Operation: Stream-Object - Open ("Filename", Mode)
Classes For File Stream Operation: Stream-Object - Open ("Filename", Mode)
It refers to a sequence of bytes. Text file. It is a file that stores information in ASCII characters. In text files, each line of text is terminated with a special character known as EOL (End of Line) character or delimiter character. When this EOL character is read or written, certain internal translations take place. Binary file. It is a file that contains information in the same format as it is held in memory. In binary files, no delimiters are used for a line and no translations occur here.
Opening a file
OPENING FILE USING CONSTRUCTOR ofstream fout(results); //output only
ifstream fin(data); //input only OPENING FILE USING open() Stream-object.open(filename, mode) ofstream ofile; ofile.open(data1);
Meaning
ios::app
ios::ate
ios::binary
ios::in
ios::out
ios::nocreate
ios::noreplace
ios::trunc
All these flags can be combined using the bitwise operator OR (|). For example, if we want to open the file example.bin in binary mode to add data we could do it by the following call to member function open(): fstream file; file.open ("example.bin", ios::out | ios::app | ios::binary);
CLOSING FILE
fout.close(); fin.close();
FUNCTION
eof()
returns true (non zero) if end of file is encountered while reading; otherwise return false(zero)
fail()
bad()
returns true if an invalid operation is attempted or any unrecoverable error has occurred.
good()
write() and read() function write() and read() functions write and read blocks of binary data. example: file.read((char *)&obj, sizeof(obj)); file.write((char *)&obj, sizeof(obj));
These internal stream pointers that point to the reading or writing locations within a stream can be manipulated using the following member functions:
seekg()
seekp()
tellg()
tellp()
The other prototype for these functions is: seekg(offset, refposition ); seekp(offset, refposition ); The parameter offset represents the number of bytes the file pointer is to be moved from the location specified by the parameter refposition. The refposition takes one of the following three constants defined in the ios class.
start of the file current position of the pointer end of the file
file.seekg(-10, ios::cur);
#include<fstream.h> #include<conio.h> int main() { ifstream fin; fin.open("out.txt"); clrscr(); char ch; int count=0; while(!fin.eof()) { fin.get(ch); count++; } cout<<"Number of characters in file is "<<count; fin.close(); getch(); return 0; }