C++中对文件进行读写操作

本文展示了一个使用C++进行文件操作的例子,包括从控制台读取字符并筛选字母保存到文件f1.dat中,再从f1.dat读取内容转换为大写并保存到f3.dat中。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include "stdafx.h"

#include<fstream>
#include<iostream>
#include<cmath>

using namespace std;

//从键盘上读取字符的函数
void read_save(){
char c[80];
ofstream outfile("f1.dat"); //以输出方工打开文件
if(!outfile){
cerr<<"open error!"<<endl; //注意是用的是cerr
exit(1);
}
cin.getline(c,80); //从键盘读入一行字符
for(int i=0;c[i]!=0;i++) //对字符一个一个的处理,直到遇到'/0'为止
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 creat_data(){
char ch;
ifstream infile("f1.dat",ios::in);//以输入的方式打开文件
if(!infile){
cerr<<"open error!"<<endl;
exit(1);
}
ofstream outfile("f3.dat"); //定义输出流f3.dat文件
if(!outfile){
cerr<<"open error!"<<endl;
exit(1);
}
while(infile.get(ch)){ //当读取字符成功时
if(ch<=122&&ch>=97)
ch=ch-32;
outfile.put(ch);
cout<<ch;
}
cout<<endl;
infile.close();
outfile.close();
}

int main(){
read_save();
creat_data();
system("pause");
return 0;
}

#include "stdafx.h"

#include<fstream>
#include<iostream>
#include<cmath>

void read_save();
void creat_data();

using namespace std;

int main(){
read_save();
creat_data();
system("pause");
return 0;
}

//从键盘上读取字符的函数
void read_save(){
char c[80];
ofstream outfile("f1.dat"); //以输出方工打开文件
if(!outfile){
cerr<<"open error!"<<endl; //注意是用的是cerr
exit(1);
}
cin.getline(c,80); //从键盘读入一行字符
for(int i=0;c[i]!=0;i++) //对字符一个一个的处理,直到遇到'/0'为止
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 creat_data(){
char ch;
ifstream infile("f1.dat",ios::in);//以输入的方式打开文件
if(!infile){
cerr<<"open error!"<<endl;
exit(1);
}
ofstream outfile("f3.dat"); //定义输出流f3.dat文件
if(!outfile){
cerr<<"open error!"<<endl;
exit(1);
}
while(infile.get(ch)){ //当读取字符成功时
if(ch<=122&&ch>=97)
ch=ch-32;
outfile.put(ch);
cout<<ch;
}
cout<<endl;
infile.close();
outfile.close();
}

C:\Symbian\8.0a\S60_2nd_FP2_SC\Projects\TestArray项目目录下会生成f1.dat,f3.dat文件,并且里面保存有每次程序运行时从console输入的字符.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值