- #include <fstream>
- ofstream //file write operation memory write to storage device
- ifstream //File read operation, storage device read area to memory
- fstream //Read and write operations, read and write operations on open files
The way to open a file is defined in the ios class (so the base class for streaming I/O), and there are several ways:
ios::in | open file for input (read) |
ios::out | open file for output (write) |
ios::ate | Initial position: end of file |
ios::app | All output is appended at the end of the file |
ios::trunc | If the file already exists, delete the file first |
ios::binary | binary mode |
- ofstream out;
- out.open( "Hello.txt" , ios::in|ios::out|ios::binary) //Make an appropriate selection according to your own needs
- ofstream out("...", ios::out);
- ifstream in("...", ios::in);
- fstream foi("...", ios::in|ios::out);
1. Write to file:
Use the overloaded insert operator <<
- // writing on a text file
- #include <fiostream.h>
- int main() {
- ofstream out("out.txt");
- if (out.is_open())
- {
- out << "This is a line.\n";
- out << "This is another line.\n";
- out.close();
- }
- return 0;
- }
- //result: write in out.txt:
- This is a line.
- This is another line
2. Read data from a file:
- // reading a text file
- #include <iostream.h>
- #include <fstream.h>
- #include <stdlib.h>
- int main() {
- char buffer[256];
- ifstream in("test.txt");
- if (! in.is_open())
- { cout << "Error opening file"; exit (1); }
- while (!in.eof() )
- {
- in.getline (buffer,100);
- cout << buffer << endl;
- }
- return 0;
- }
eof():如果读文件到达文件末尾,返回true。
3.二进制文件
在二进制文件中,使用<< 和>>,以及函数(如getline)来操作符输入和输出数据,没有什么实际意义,虽然它们是符合语法的。
文件流包括两个为顺序读写数据特殊设计的成员函数:write 和 read。第一个函数 (write) 是ostream 的一个成员函数,都是被ofstream所继承。而read 是istream 的一个成员函数,被ifstream 所继承。类 fstream 的对象同时拥有这两个函数。它们的原型是:
write ( char * buffer, streamsize size );
read ( char * buffer, streamsize size );
read ( char * buffer, streamsize size );
这里 buffer 是一块内存的地址,用来存储或读出数据。参数size 是一个整数值,表示要从缓存(buffer)中读出或写入的字符数。
- // reading binary file
- #include <iostream>
- #include <fstream.h>
- constchar * filename = "test.txt";
- int main() {
- char * buffer;
- long size;
- ifstream in (filename, ios::in|ios::binary|ios::ate);
- size = in.tellg();
- in.seekg (0, ios::beg);
- buffer = newchar [size];
- in.read (buffer, size);
- in.close();
- cout << "the complete file is in a buffer";
- delete[] buffer;
- return 0;
- }
- //operation result:
- The complete file is in a buffer