您的位置:首页 > 编程语言 > C语言/C++

文件运行C++读书笔记之 文件与流 文件读写操作 通过指针获取文件大小

2013-05-18 18:17 483 查看
时间紧张,先记一笔,后续优化与完善。

在本例程中不仅概括了文件的基本读写操纵,如何获得文件的巨细,还牵扯到getline和cin.getline的区别,及string类字符串如何转换为c风格字符串的问题,这些问题将在下一篇博文中介绍。首先先看程序运行结果,运行结果如下:

/**********************************
程序运行结果如下:
Writingtothefile
Enteryourname:wangshihui
Enteryourage:22
Readingfromthefile
wangshihui
22
wangshihui

22

Torecap,thethreemainobjectivesintheMysteryMethodare:
Toattractawoman
Toestablishcomfort,trust,andconnection
Tostructuretheopportunitytobeseduced
Awoman'snumber-oneemotionalpriorityissafetyandsecurity.

TheMisteryMethod.txtsizeis:294bytes.

Processreturned0(0x0)executiontime:13.100s
Pressanykeytocontinue.

***********************************/

#include<fstream> #include<iostream> usingnamespacestd; voidtest_write_read_cin_getline() { chardata[100]; //openafileinwritemode. ofstreamoutfile; outfile.open("TheMisteryMethod.txt"); cout<<"Writingtothefile"<<endl; cout<<"Enteryourname:"; cin.getline(data,100); //writeinputteddataintothefile. outfile<<data<<endl; cout<<"Enteryourage:"; cin>>data; cin.ignore(); //againwriteinputteddataintothefile. outfile<<data<<endl; //closetheopenedfile. outfile.close(); //openafileinreadmode. ifstreaminfile; infile.open("TheMisteryMethod.txt"); cout<<"Readingfromthefile"<<endl; infile>>data; //writethedataatthescreen. cout<<data<<endl; //againreadthedatafromthefileanddisplayit. infile>>data; cout<<data<<endl; //closetheopenedfile. infile.close(); } voidtest_write() { ofstreammyfile; myfile.open("TheMisteryMethod.txt",ios::app); if(myfile.is_open()) { myfile<< "\nTorecap,thethreemainobjectivesintheMysteryMethodare:\n\ Toattractawoman\n\ Toestablishcomfort,trust,andconnection\n\ Tostructuretheopportunitytobeseduced\n"; myfile.close(); } else cout<<"打开文件失败!\n"; } voidtest_write_read_getline() { stringstr; //Createsaninstanceofofstream,andopensTheMisteryMethod.txt ofstreama_file("TheMisteryMethod.txt",ios::app);//追加方法 //OutputstoTheMisteryMethod.txtthrougha_file if(a_file.is_open()) { a_file<<"Awoman'snumber-oneemotionalpriorityissafetyandsecurity."; //Closethefilestreamexplicitly a_file.close(); } else cout<<"Unabletoopenfile\n"; //Opensforreadingthefile追加方法 ifstreamb_file("TheMisteryMethod.txt",ios::app); //Readsonestringfromthefile b_file>>str;//只显示to表示遇到空格停止接收字符 cout<<str<<"\n"; getline(b_file,str,'\0');//输出缓冲区剩余的字符 cout<<str<<"\n"; cin.get();//waitforakeypress //b_fileisclosedimplicitlyhere } voidGetSizeOfFile(stringfilename) { longbegin,end; ifstreammyfile(filename.c_str());//必须转换为c风格字符串 begin=myfile.tellg(); myfile.seekg(0,ios::end); end=myfile.tellg(); myfile.close(); cout<<filename<<"sizeis:"<<(end-begin)<<"bytes.\n"; } intmain() { test_write_read_cin_getline(); test_write(); test_write_read_getline(); stringfile("TheMisteryMethod.txt"); GetSizeOfFile(file); return0; } /********************************** 程序运行结果如下: Writingtothefile Enteryourname:wangshihui Enteryourage:22 Readingfromthefile wangshihui 22 wangshihui 22 Torecap,thethreemainobjectivesintheMysteryMethodare: Toattractawoman Toestablishcomfort,trust,andconnection Tostructuretheopportunitytobeseduced Awoman'snumber-oneemotionalpriorityissafetyandsecurity. TheMisteryMethod.txtsizeis:294bytes. Processreturned0(0x0)executiontime:13.100s Pressanykeytocontinue. ***********************************/
C++hastwobasicclassestohandlefiles,ifstreamandofstream.Tousethem,includetheheaderfilefstream.Ifstreamhandlesfileinput(readingfromfiles),andofstreamhandlesfileoutput(writingtofiles).Thewaytodeclareaninstanceoftheifstreamorofstreamclassis:

ifstreama_file;
or

ifstreama_file("filename");

Theconstructorforbothclasseswillactuallyopenthefileifyoupassthenameasanargument.Aswell,bothclasseshaveanopencommand(a_file.open())andaclosecommand(a_file.close()).Youaren'trequiredtousetheclosecommandasitwillautomaticallybecalledwhentheprogramterminates,butifyouneedtoclosethefilelongbeforetheprogramends,itisuseful.

ThebeautyoftheC++methodofhandlingfilesrestsinthesimplicityoftheactualfunctionsusedinbasicinputandoutputoperations.BecauseC++supportsoverloadingoperators,itispossibletouse<<and>>infrontoftheinstanceoftheclassasifitwerecoutorcin.Infact,filestreamscanbeusedexactlythesameascoutandcinaftertheyareopened.

Input/Outputwithfiles

C++providesthefollowingclassestoperformoutputandinputofcharactersto/fromfiles:

ofstream:Streamclasstowriteonfiles

ifstream:Streamclasstoreadfromfiles

fstream:Streamclasstobothreadandwritefrom/tofiles.

Openafile

Inordertoopenafilewithastreamobjectweuseitsmemberfunctionopen():

open(filename,mode);

Wherefilenameisanull-terminatedcharactersequenceoftypeconstchar*(thesametypethatstringliteralshave)representingthenameofthefiletobeopened,andmodeisanoptionalparameterwithacombinationofthefollowingflags:

ios::inOpenforinputoperations.
ios::outOpenforoutputoperations.
ios::binaryOpeninbinarymode.
ios::ateSettheinitialpositionattheendofthefile.
Ifthisflagisnotsettoanyvalue,theinitialpositionisthebeginningofthefile.
ios::appAlloutputoperationsareperformedattheendofthefile,appendingthecontenttothecurrentcontentofthefile.Thisflagcanonlybeusedinstreamsopenforoutput-onlyoperations.
ios::truncIfthefileopenedforoutputoperationsalreadyexistedbefore,itspreviouscontentisdeletedandreplacedbythenewone.
每日一道理

如果说生命是一座庄严的城堡,如果说生命是一株苍茂的大树,如果说生命是一只飞翔的海鸟。那么,信念就是那穹顶的梁柱,就是那深扎的树根,就是那扇动的翅膀。没有信念,生命的动力便荡然无存;没有信念,生命的美丽便杳然西去。(划线处可以换其他词语)

AlltheseflagscanbecombinedusingthebitwiseoperatorOR(|).Forexample,ifwewanttoopenthefileexample.bininbinarymodetoadddatawecoulddoitbythefollowingcalltomemberfunctionopen():

1
2

ofstreammyfile;
myfile.open("example.bin",ios::out|ios::app|ios::binary);

Eachoneoftheopen()memberfunctionsoftheclassesofstream,ifstreamandfstreamhasadefaultmodethatisusedifthefileisopenedwithoutasecondargument:

classdefaultmodeparameter
ofstreamios::out
ifstreamios::in
fstreamios::in|ios::out
Forifstreamandofstreamclasses,ios::inandios::outareautomaticallyandrespectivelyassumed,evenifamodethatdoesnotincludethemispassedassecondargumenttotheopen()memberfunction.

Thedefaultvalueisonlyappliedifthefunctioniscalledwithoutspecifyinganyvalueforthemodeparameter.Ifthefunctioniscalledwithanyvalueinthatparameterthedefaultmodeisoverridden,notcombined.

Tocheckifafilestreamwassuccessfulopeningafile,youcandoitbycallingtomemberis_open()withnoarguments.Thismemberfunctionreturnsaboolvalueoftrueinthecasethatindeedthestreamobjectisassociatedwithanopenfile,orfalseotherwise:


if(myfile.is_open()){/*ok,proceedwithoutput*/}

Closingafile

Whenwearefinishedwithourinputandoutputoperationsonafileweshallcloseitsothatitsresourcesbecomeavailableagain.Inordertodothatwehavetocallthestream'smemberfunctionclose().Thismemberfunctiontakesnoparameters,andwhatitdoesistoflushtheassociatedbuffersandclosethefile:


myfile.close();

Oncethismemberfunctioniscalled,thestreamobjectcanbeusedtoopenanotherfile,andthefileisavailableagaintobeopenedbyotherprocesses.

getandputstreampointers

Alli/ostreamsobjectshave,atleast,oneinternalstreampointer:

ifstream,likeistream,hasapointerknownasthegetpointerthatpointstotheelementtobereadinthenextinputoperation.

ofstream,likeostream,hasapointerknownastheputpointerthatpointstothelocationwherethenextelementhastobewritten.

Finally,fstream,inheritsboth,thegetandtheputpointers,fromiostream(whichisitselfderivedfrombothistreamandostream).

Theseinternalstreampointersthatpointtothereadingorwritinglocationswithinastreamcanbemanipulatedusingthefollowingmemberfunctions:

tellg()andtellp()

Thesetwomemberfunctionshavenoparametersandreturnavalueofthemembertypepos_type,whichisanintegerdatatyperepresentingthecurrentpositionofthegetstreampointer(inthecaseoftellg)ortheputstreampointer(inthecaseoftellp).

seekg()andseekp()

Thesefunctionsallowustochangethepositionofthegetandputstreampointers.Bothfunctionsareoverloadedwithtwodifferentprototypes.Thefirstprototypeis:

seekg(position);
seekp(position);

Usingthisprototypethestreampointerischangedtotheabsolutepositionposition(countingfromthebeginningofthefile).Thetypeforthisparameteristhesameastheonereturnedbyfunctionstellgandtellp:themembertypepos_type,whichisanintegervalue.

Theotherprototypeforthesefunctionsis:

seekg(offset,direction);
seekp(offset,direction);

Usingthisprototype,thepositionofthegetorputpointerissettoanoffsetvaluerelativetosomespecificpointdeterminedbytheparameterdirection.offsetisofthemembertypeoff_type,whichisalsoanintegertype.Anddirectionisoftypeseekdir,whichisanenumeratedtype(enum)thatdeterminesthepointfromwhereoffsetiscountedfrom,andthatcantakeanyofthefollowingvalues:

ios::begoffsetcountedfromthebeginningofthestream
ios::curoffsetcountedfromthecurrentpositionofthestreampointer
ios::endoffsetcountedfromtheendofthestream
==============================================================

Thedefaultmodeforopeningafilewithofstream'sconstructoristocreateitifitdoesnotexist,ordeleteeverythinginitifsomethingdoesexistinit.Ifnecessary,youcangiveasecondargumentthatspecifieshowthefileshouldbehandled.Theyarelistedbelow:

ios::app--Appendtothefile
ios::ate--Setthecurrentpositiontotheend
ios::trunc--Deleteeverythinginthefile
Forexample:

ofstreama_file("test.txt",ios::app);
Thiswillopenthefilewithoutdestroyingthecurrentcontentsandallowyoutoappendnewdata.Whenopeningfiles,beverycarefulnottousethemifthefilecouldnotbeopened.Thiscanbetestedforveryeasily:

ifstreama_file("example.txt");

if(!a_file.is_open())
{
//Thefilecouldnotbeopened
}
else
{
//Safelyusethefilestream
}

文章结束给大家分享下程序员的一些笑话语录:

PC软件体积大,是因为一个PC软件功能往往较多,能够满足你一个方面的需求,而一个iphone软件往往没几行代码,干一件很小的事情,自然需要的软件就多。就像吃西瓜和吃瓜子的来比数目,单位不同啊。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐