C++输入/输出(2)

 1 #include <fstream.h>
 2 #include <iostream.h>
 3 #include <stdlib.h>
 4 
 5 void main()
 6 {
 7     ifstream inFile;
 8     ofstream outFile;
 9     outFile.open("my.txt", ios::out);
10     char univ[] = "xxdfly", name[10];
11     int course  = 0216, number;
12     outFile << univ << endl;
13     outFile << course << endl;
14     inFile.open("my.txt", ios::in|ios::nocreate);
15     if(!inFile)
16     {
17         cerr << "Can't Open The File" << endl;
18         exit(1);
19     }
20     char c;
21     inFile >> name >> c >> number;
22     outFile << "name: " << name << endl;
23     outFile << "number: " << number << endl;
24 }    

C++中的文件输入输出方式:

(1)在程序开头必须用预处理指令#include 包含头文件<fstream.h>,他定义了类 ifstream, ofstream, fstream;

(2)要创建一个输入流,必须声明它为 ifstream 类的实例;

(3)要创建一个输出流,必须声明它为 ofstream类的实例;

(4)执行输入和输出的操作的流必须声明它为 fstream 类的实例。

 

ifstream, ofstream, fstream 类都是从 istream和ostream 派生出来的,而类istream,ostream 又是从类ios 派生出来的,因此这些类都可使用类 ios 的所有运算。

在文件打开操作中,指定的文件模式有以下几种:

ios::app:    把所有对文件的输出添加在文件尾。它只用于输出文件。

ios::binary:    文件以二进制方式打开。 此项缺省时文件以文本方式打开。

ios::nocreate:  文件若不存在则将导致打开操作失败。

ios::out:    表明该文件用于输出。此项可缺省。

ios::in:      表明该文件用于输入。此项可缺省。

 

--摘自《数据结构(用面向对象方法与C++描述)》   

posted @ 2015-03-23 16:15  薛晓东  阅读(120)  评论(0编辑  收藏  举报