ورود

View Full Version : مبتدی: نحوه خواندن فایل در سی ++



mirhaj
شنبه 27 اسفند 1390, 00:00 صبح
می خاستم بدونم در سی++ چی جوری از فایل استفاده میشه؟

بهروز عباسی
شنبه 27 اسفند 1390, 00:55 صبح
این یه برنامه کوچولو برای کار با فایله شاید بکارت بیاد
#include<iostream.h>
#include <fstream.h>
#include <conio.h>
struct f_record
{
char name[20];
int sn;
float avg;
}f_rec1;

void firstmenu();
void creatfile();
void inputfile();
void outputfile();


int main()
{
int choice;

while(1){
firstmenu();
while(1)
{
cin>>(choice);
if(choice>0&&choice<10)
break;
}
if(choice==2) outputfile();
if(choice==1) creatfile();
if(choice==9) cout<<"Programmer : Behrooz Abbasi";
if(choice==8) break;
}
cout<<("--------------------------------------------------------------------------------");
cout<<("\nCoded by : Behrooz Abbasi\n");
cout<<("\r\nPress any key to exit...");
getch();

return 0;
}
void outputfile()
{
fstream file_in;
cout<<("\n << Shoew File >> \r\n");
cout<<("+-------------------------------------------------------------------------------");
file_in.open("myfile.bin",ios::binary|ios::in);
if(!file_in)cout<<"File codnot open...\n";
file_in.read((char*)&f_rec1,sizeof(f_record));
while(!file_in.eof())
{
cout<<"Name ="<<f_rec1.name;
cout<<"\nSN ="<<f_rec1.sn;
cout<<"\nAVG ="<<f_rec1.avg;
cout<<("\n+-------------------------------------------------------------------------------");
file_in.read((char*)&f_rec1,sizeof(f_record));
}
file_in.close();
}

/*----------------------------------------------------*/
void creatfile()
{
int count;
fstream file_out;
cout<<"Enter count of add item:= ";cin>>count;
file_out.open("myfile.bin",ios::binary|ios::out);
for(int i=1;i<=count;i++)
{
inputfile();
file_out.write((char*)&f_rec1,sizeof(f_record));
}
file_out.close();
}

void inputfile()
{
cout<<("\n << Creat File >> \r\n");
cout<<("+-------------------------------------------------------------------------------");
cout<<"Enter Name :";
cin>>f_rec1.name;
cout<<"Enter SN :";
cin>>f_rec1.sn;
cout<<"Enter AVG :";
cin>>f_rec1.avg;
cout<<("+-------------------------------------------------------------------------------");
}
//----------------------------
void firstmenu()
{

cout<<("\n << Work With File in C++ >> \r\n");
cout<<("+-------------------------------------------------------------------------------");
cout<<("1. Create File.\n");
cout<<("2. Show File.\n");
cout<<("3. Append To File.\n");
cout<<("4. Edit File.\n");
cout<<("6. Search in File.\n");
cout<<("7. Delete Record.\n");
cout<<("8. Exit.\n");
cout<<("9. About.\n");
cout<<("+-------------------------------------------------------------------------------");
cout<<("Enter your Choice...");
}