1. 程式人生 > 其它 >C++中對檔案進行讀寫操作

C++中對檔案進行讀寫操作

#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輸入的字元.