文件运行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.
open(filename,mode);
Wherefilenameisanull-terminatedcharactersequenceoftypeconstchar*(thesametypethatstringliteralshave)representingthenameofthefiletobeopened,andmodeisanoptionalparameterwithacombinationofthefollowingflags:
每日一道理
如果说生命是一座庄严的城堡,如果说生命是一株苍茂的大树,如果说生命是一只飞翔的海鸟。那么,信念就是那穹顶的梁柱,就是那深扎的树根,就是那扇动的翅膀。没有信念,生命的动力便荡然无存;没有信念,生命的美丽便杳然西去。(划线处可以换其他词语)
AlltheseflagscanbecombinedusingthebitwiseoperatorOR(|).Forexample,ifwewanttoopenthefileexample.bininbinarymodetoadddatawecoulddoitbythefollowingcalltomemberfunctionopen():
Eachoneoftheopen()memberfunctionsoftheclassesofstream,ifstreamandfstreamhasadefaultmodethatisusedifthefileisopenedwithoutasecondargument:
Forifstreamandofstreamclasses,ios::inandios::outareautomaticallyandrespectivelyassumed,evenifamodethatdoesnotincludethemispassedassecondargumenttotheopen()memberfunction.
Thedefaultvalueisonlyappliedifthefunctioniscalledwithoutspecifyinganyvalueforthemodeparameter.Ifthefunctioniscalledwithanyvalueinthatparameterthedefaultmodeisoverridden,notcombined.
Tocheckifafilestreamwassuccessfulopeningafile,youcandoitbycallingtomemberis_open()withnoarguments.Thismemberfunctionreturnsaboolvalueoftrueinthecasethatindeedthestreamobjectisassociatedwithanopenfile,orfalseotherwise:
Oncethismemberfunctioniscalled,thestreamobjectcanbeusedtoopenanotherfile,andthefileisavailableagaintobeopenedbyotherprocesses.
ifstream,likeistream,hasapointerknownasthegetpointerthatpointstotheelementtobereadinthenextinputoperation.
ofstream,likeostream,hasapointerknownastheputpointerthatpointstothelocationwherethenextelementhastobewritten.
Finally,fstream,inheritsboth,thegetandtheputpointers,fromiostream(whichisitselfderivedfrombothistreamandostream).
Theseinternalstreampointersthatpointtothereadingorwritinglocationswithinastreamcanbemanipulatedusingthefollowingmemberfunctions:
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:
==============================================================
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软件往往没几行代码,干一件很小的事情,自然需要的软件就多。就像吃西瓜和吃瓜子的来比数目,单位不同啊。
在本例程中不仅概括了文件的基本读写操纵,如何获得文件的巨细,还牵扯到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.
***********************************/
C++hastwobasicclassestohandlefiles,ifstreamandofstream.Tousethem,includetheheaderfilefstream.Ifstreamhandlesfileinput(readingfromfiles),andofstreamhandlesfileoutput(writingtofiles).Thewaytodeclareaninstanceoftheifstreamorofstreamclassis:
or
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::in | Openforinputoperations. |
ios::out | Openforoutputoperations. |
ios::binary | Openinbinarymode. |
ios::ate | Settheinitialpositionattheendofthefile. Ifthisflagisnotsettoanyvalue,theinitialpositionisthebeginningofthefile. |
ios::app | Alloutputoperationsareperformedattheendofthefile,appendingthecontenttothecurrentcontentofthefile.Thisflagcanonlybeusedinstreamsopenforoutput-onlyoperations. |
ios::trunc | Ifthefileopenedforoutputoperationsalreadyexistedbefore,itspreviouscontentisdeletedandreplacedbythenewone. |
如果说生命是一座庄严的城堡,如果说生命是一株苍茂的大树,如果说生命是一只飞翔的海鸟。那么,信念就是那穹顶的梁柱,就是那深扎的树根,就是那扇动的翅膀。没有信念,生命的动力便荡然无存;没有信念,生命的美丽便杳然西去。(划线处可以换其他词语)
AlltheseflagscanbecombinedusingthebitwiseoperatorOR(|).Forexample,ifwewanttoopenthefileexample.bininbinarymodetoadddatawecoulddoitbythefollowingcalltomemberfunctionopen():
1 2 | ofstreammyfile; myfile.open("example.bin",ios::out|ios::app|ios::binary); |
class | defaultmodeparameter |
---|---|
ofstream | ios::out |
ifstream | ios::in |
fstream | ios::in|ios::out |
Thedefaultvalueisonlyappliedifthefunctioniscalledwithoutspecifyinganyvalueforthemodeparameter.Ifthefunctioniscalledwithanyvalueinthatparameterthedefaultmodeisoverridden,notcombined.
Tocheckifafilestreamwassuccessfulopeningafile,youcandoitbycallingtomemberis_open()withnoarguments.Thismemberfunctionreturnsaboolvalueoftrueinthecasethatindeedthestreamobjectisassociatedwithanopenfile,orfalseotherwise:
if(myfile.is_open()){/*ok,proceedwithoutput*/} |
Closingafile
Whenwearefinishedwithourinputandoutputoperationsonafileweshallcloseitsothatitsresourcesbecomeavailableagain.Inordertodothatwehavetocallthestream'smemberfunctionclose().Thismemberfunctiontakesnoparameters,andwhatitdoesistoflushtheassociatedbuffersandclosethefile:myfile.close(); |
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::beg | offsetcountedfromthebeginningofthestream |
ios::cur | offsetcountedfromthecurrentpositionofthestreampointer |
ios::end | offsetcountedfromtheendofthestream |
Thedefaultmodeforopeningafilewithofstream'sconstructoristocreateitifitdoesnotexist,ordeleteeverythinginitifsomethingdoesexistinit.Ifnecessary,youcangiveasecondargumentthatspecifieshowthefileshouldbehandled.Theyarelistedbelow:
ios::ate--Setthecurrentpositiontotheend
ios::trunc--Deleteeverythinginthefile
Forexample:
Thiswillopenthefilewithoutdestroyingthecurrentcontentsandallowyoutoappendnewdata.Whenopeningfiles,beverycarefulnottousethemifthefilecouldnotbeopened.Thiscanbetestedforveryeasily:
if(!a_file.is_open())
{
//Thefilecouldnotbeopened
}
else
{
//Safelyusethefilestream
}
文章结束给大家分享下程序员的一些笑话语录:
PC软件体积大,是因为一个PC软件功能往往较多,能够满足你一个方面的需求,而一个iphone软件往往没几行代码,干一件很小的事情,自然需要的软件就多。就像吃西瓜和吃瓜子的来比数目,单位不同啊。
相关文章推荐
- C++读书笔记之 文件与流 文件读写操作 通过指针获取文件大小
- Java 获取文件大小及文件读写操作
- ios 关于文件操作 获取 文件大小
- 使用动态分配和指针操作求 9 个 double 数的乘积(编译通过了,但是运行时出错,谁能帮我看看出了什么问题啊)[em08]
- Asp.Net 文件操作基类(读取,删除,批量拷贝,删除,写入,获取文件夹大小,文件属性,遍历目录)
- 对于文件的读写操作处理,指针头
- 通过jquery获取上传文件名称、类型和大小的实现代码
- java 两个通过java代码操作FTP的类,上传下载删除,获取文件
- Linux系统遍历文件夹 获取文件大小的操作(C语言实现)
- android java file 清理垃圾获取文件大小 删除文件等操作
- 通过_stat结构体获取文件大小
- Asp.Net 文件操作基类(读取,删除,批量拷贝,删除,写入,获取文件夹大小,文件属性,遍历目录)
- Asp.Net 文件操作基类(读取,删除,批量拷贝,删除,写入,获取文件夹大小,文件属性,遍历目录)
- 通过URL获取文件的大小
- (二)操作libcurl实现获取目的文件大小, 下载进度显示, 断点续传
- java 通过url获取文件大小
- phonegap 通过URI获取文件大小
- oc 文件管理NSFileManager,文件读写NSFileHandle ,设计一个文件管理类将一个文件复制到另一个文件,由于文件过大要求每次复制100长度,通过NSFileHandle 来操作,并
- 通过文件的方式对硬盘扇区进行直接读写操作
- C# XML文件格式化、xml文件读写(通过自定义类xmlNode实现对xml的操作)