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

来源:互联网 发布:小户型沙发淘宝 编辑:程序博客网 时间:2024/05/03 08:24

#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();
}

原创粉丝点击