برای کار با فایل در سی++ راه های زیادی وجود دارد که یادگیری همه ی مفید است . بهتر از برای کار با فایل در مراحل اول با یک یا دو نوع کلی مار کرد و بعد از مهارت پیدا کردن در این زمینه به سراغ سایر روش ها بروید .
در اینجا بک برنامه ی ساده که از کابر تعدادی اسم می گیرد و در یک فایل می ریزد (با ترتیبی معکوس)و دوباره از فایل می خواند(باز هم با ترتیبی معکوس) و…(بقیه اش رو خودتون بخوانید):
#include <iostream.h>
#include <conio.h>
#include <fstream.h>
#include <cstring.h>
void swap(string &r,string &t){
string o=r;
r=t;
t=o;
}
void print(string *str){
for(int q=0;str[q]!=NULL;q++)
cout<<str[q]<<” “;
cout<<endl;
}
main(){
fstream file_1(“c:/file1.txt”,ios::in|ios::out);
string *str_1=new string[100];
string *str_2=new string[100];
string name;
int s=0;
while(true){
cin>>name;
if(name[0]==’$')
break;
//for(int i=0;i<name.length();i++)
str_1[s]=name;
s++;
// file_1<<endl;
// cout<<endl<<name;
}//end while I
//————-revers——————–
for(int i=0;i<s;i++)
str_2[s-i-1]=str_1[i];
for(int i=0;i<s;i++)
file_1<<str_2[i]<<endl;
file_1.close();
for(int i=0;i<s;i++)
str_1[i]=str_2[i]=’ ‘;
//——————————————
cout<<”while <I> was ended”<<endl<<endl;
//——————————————
ifstream file_3(“c:/file1.txt”);
ofstream file_2(“c:/file2.txt”);
s=0;
while(!file_3.eof()){
getline(file_3,name);
str_1[s++]= name;
for(int i=0;i<s;i++)
str_2[s-i-1]=str_1[i];
//cout<<name;
}
for(int i=0;i<s;i++)
file_2<<str_2[i]<<endl;
file_2.close();
file_3.close();
//—————————————–
cout<<”end while <II>”<<endl<<endl;
ifstream file_4(“c:/file2.txt”);
while(!file_4.eof()){
getline(file_4,name);
cout<<name<<endl;
}
file_4.close();
//====================sort===============
ifstream file_5(“c:/file2.txt”);
int size=0;
fstream file_6(“c:/file3.txt” ,ios::in|ios::out);
int n=100;
string *str=new string[n];
int i=0 ;
while(!file_5.eof()) {
getline(file_5,str[i++]);
size++;
//file_6<<str[i]<<endl ;
//cout<<str[i++]<<endl ;
if(i==n){
n*=2;
string *str_1=new string[n];
for(int r=0;r<(n/2);r)
str_1[r]=str[r];
str=str_1;
}
}
// for(int p=0;str[p]!=NULL;p++)
// cout<<str[p]<<endl;
// bool b=true ;
int u=0;
for(int t=0;t<size-1;t++) {
for(int i=0;i<size-1;i++)
if(str[i]>str[i+1])
{
swap(str[i],str[i+1]);
/*string o=str[i+1];
str[i+1]=str[i];
str[i]=o;
*/
// for(int q=0;str[q]!=NULL;q++)
// cout<<str[q]<<” “;
// cout<<endl;
print(str);
}
}
for(int i=0;i<size;i++)
file_6<<str[i]<<endl;
getch();
}
برچسبها: سی++