文件的输入和输出
2009-05-25 00:09
225 查看
iostream库也支持文件的输入和输出。所有能应用在标准输入和输出上的操作符,也都可以应用到已经被打开的输入或输出文件上。为了打开一个文件供输入和输出,除了iostream头文件之外,还必须包含头文件:
#include <fstream>
为了打开一个输出文件,我们必须声明一个ofstream类型的对象:
ofstream outfile("name-of-file");
为了测试是否已经成功地打开一个文件,我们可以写出这样的代码:
//如文件不能打开值为false
if(!outfile)
cerr<<"Sorry! We were unable to open the file!/n";
类似地,为了打开一个文件供输入,我们必须声明一个ifstream类型的对象:
ifstream infile("name-of-file");
if ( ! infile )
cerr << "Sorry! We were unable to open the file!/n";
下面是一个简单的程序。它从一个名为in_file的文本文件中读取单词,然后把每个单词写到一个out_file的输出文件中,并且为每个词用空格分开。
#include <iostream>
#include <fstream>
#include <string>
int main()
{
ofstream outfile( "out_file" );
ifstream infile( "in_file" );
if ( ! infile ) {
cerr << "error: unable to open input file!/n";
return -1;
}
if ( ! outfile ) {
cerr << "error: unable to open output file!/n";
return -2;
}
string word;
while ( infile >> word )
outfile << word << ' ';
return 0;
}
#include <fstream>
为了打开一个输出文件,我们必须声明一个ofstream类型的对象:
ofstream outfile("name-of-file");
为了测试是否已经成功地打开一个文件,我们可以写出这样的代码:
//如文件不能打开值为false
if(!outfile)
cerr<<"Sorry! We were unable to open the file!/n";
类似地,为了打开一个文件供输入,我们必须声明一个ifstream类型的对象:
ifstream infile("name-of-file");
if ( ! infile )
cerr << "Sorry! We were unable to open the file!/n";
下面是一个简单的程序。它从一个名为in_file的文本文件中读取单词,然后把每个单词写到一个out_file的输出文件中,并且为每个词用空格分开。
#include <iostream>
#include <fstream>
#include <string>
int main()
{
ofstream outfile( "out_file" );
ifstream infile( "in_file" );
if ( ! infile ) {
cerr << "error: unable to open input file!/n";
return -1;
}
if ( ! outfile ) {
cerr << "error: unable to open output file!/n";
return -2;
}
string word;
while ( infile >> word )
outfile << word << ' ';
return 0;
}
相关文章推荐
- C程序freopen()实现快速从文件输入和输出(重定向)到文件(ACM练习好帮手)
- 文件的输入输出流方法
- python基础(文件输入/输出 内建类型 字典操作使用方法)
- 编写一个函数,能输出文件夹下的文件列表,文件名通过控制台输入
- 文件的输入/输出操作
- 输入N个学生的信息(包括:学号,姓名,5科成绩,总分),统计所有学生的总分,存入二进制文件stu_sc.dat中。然后读取该文件,查找总分最高的学生,并输出该生的所有信息。
- JAVA 序列化与文件的输入/输出
- Oracle9i第2版中的UNT_FILE提高了文件输入/输出(I/O)功能。
- Java里面最简单好用的文件输入输出方法
- 编写一个void sort(int*x,int n)实现将x数组中的n个数据从大到小排序。n及数组元素在主函数中输入。将结果显示在屏幕上并输出到文件
- 黑马程序员——第20天——IO输入与输出(File类,Properties,打印流,合并流,切割文件)
- 文件的输入输出基础(vc++)
- 文件输入/输出函数对比
- java文件输入输出常用格式
- java输入输出处理-文件file
- 第十三周项目 6 体验文件操作(5—实战)——从文件输入与输出到文件中
- 数据库操作_连接SQL Server数据库示例;连接ACCESS数据库;连接到 Oracle 数据库示例;SqlCommand 执行SQL命令示例;SqlDataReader 读取数据示例;使用DataAdapter填充数据到DataSet;使用DataTable存储数据库表;将数据库数据填充到 XML 文件;10 使用带输入参数的存储过程;11 使用带输入、输出参数的存储过程示;12 获得数据库中表的数目和名称;13 保存图片到SQL Server数据库示例;14 获得插入记录标识号;Exce
- 用fputc和fgetc操作文件的输入输出-复制文件
- python文件输入和输出
- C#文件的输入与输出