例13.10 从键盘读入一行字符,把其中的字母字符依次存放在磁盘文件f2.dat中。

例13.10 从键盘读入一行字符,把其中的字母字符依次存放在磁盘文件f2.dat中。

#include<iostream>
#include<fstream>
using namespace std;

void save_to_file()
{
	ofstream outfile("f2.dat");
	if(!outfile)
	{
		cerr<<"open f2.dat error!"<<endl;
		exit(1);
	}
	char c[80];
	cin.getline(c,80);

	for(int i=0;c[i]!=0;i++)
	{
		if(c[i]>=65&&c[i]<=90||c[i]>=97&&c[i]<=122)
		{
			outfile.put(c[i]);
			cout<<c[i];
		}
	}
	cout<<endl;
	outfile.close();
}

void get_from_file()
{
	char ch;
	ifstream infile("f2.dat",ios::in);//ios::nocreate是在C++标准制定之前在<fstream.h>中有定义的。C++标准中没有nocreate,因为这是一个默认的动作,无需写上。
	if(!infile)
	{
		cerr<<"open f2.dat error!"<<endl;
		exit(1);
	}
	ofstream outfile("f3.dat");
	
	if(!outfile)
	{
		cerr<<"open f3.dat error!"<<endl;
		exit(1);
	}
	while(infile.get(ch))
	{
		if(ch>=97&&ch<=122)
			ch=ch-32;
		outfile.put(ch);
		cout<<ch;
	}
	cout<<endl;
	infile.close();
	outfile.close();
}

int main()
{
	save_to_file();
	get_from_file();
	return 0;
}

在这里插入图片描述

例13.10可以编写一个专用函数,将磁盘文件内容读入内存,然后输出到显示器。

#include<iostream>
#include<fstream>
using namespace std;

void display_file(const char *filename)
{
	ifstream infile(filename,ios::in);//ios::nocreate是在C++标准制定之前在<fstream.h>中有定义的。C++标准中没有nocreate,因为这是一个默认的动作,无需写上。
	if(!infile)
	{
		cerr<<"open error!"<<endl;
		exit(1);
	}
	char ch;
	while(infile.get(ch))
	{
		cout.put(ch);
	}
	cout<<endl;
	infile.close();
}

int main()
{
	display_file("f3.dat");
	return 0;
}

在这里插入图片描述

在这里插入图片描述

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值