tellg和seekg
tellg (、seekg )、and seekp )、functionsareusedtoset/getthepositionofgetandputpointersinafilewhilereadingandwriting。
tellg (、seekg )和seekp )函数用于在读取和写入时设置/获取get和put指针在文件中的位置。
Syntaxes:
//tellg(streampostellg ); //seekg(istreamseekg ) (streampospos ); istreamseekg(streamoffoff,ios_base:seekdir way ); //seekp(streamseekp ) streampospos ); ostreamseekp (流关闭,ios_base:seekdir way ); Here,
销售点representsthenewabsolutepositionwithinthestream (from the beginning )。
pos指示流中的新绝对位置。
关闭representstheoffsettoseek。
关闭-表示要搜索的偏移。
销售点representsthefollowingconstants,
pos表示以下常量:
IOs _ base :3360 beg/IOs :3360 begbeginningofthestream.IOs _ base :3360 beg/IOs 33603360 beg流的开始。 IOs _ base :3360 cur/IOs :3360 curcurrentpositioninthestream.IOs _ base :3360 cur/IOs :3360 cur流中的当前位置IOs :3360 endendthestream.IOs _ base 33603360 end/IOs 33603360 end退出流程。 c程序是tellg ()、seekg ()、seekp () )的示例) cprogramtodemonstratetheexampleoftellg ()、seekg ()、and seekp () )、的程序
以下程序使用文件“my.txt”。 此文件包含以下文本:
File: my.txt
Program:
# include iostream # includefstreamusingnamespacestd; int main () { fstream F; //openingafileininputandoutputmodef.open (my.txt ),IOs:3360in|IOs:out ); //gettingcurrentlocationcoutf.tellg () endl; //seeing8bytes/charactersf.seekg (8,ios:beg ); //now,gettingthecurrentlocationcoutf.tellg () endl; //extractingonecharacterfromcurrentlocationcharc=f.get (; //printingthecharactercoutcendl; //after getting the character,//gettingcurrentlocationcoutf.tellg () endl; //now,seeking 10 more bytes/charactersf.seekg (10,ios:cur ); //now,gettingcurrentlocationcoutf.tellg () endl; //again,extracingtheonecharacterfromcurrentlocationc=f.get (; //printingthecharactercoutcendl; //after getting the character,//gettingcurrentlocationcoutf.tellg () endl; //again,seeking7bytes/charactersfrombeginningf.seekp (7,ios:beg ); //writtingacharacter ' z ' atcurrentlocationf.put (' z ); //now,seeking back7bytes/charactersfromtheendf.seekg (-7,ios:end ); //now,printingthecurrentlocationcout ' end : ' f.tellg () endl; //extractingonecharacterfromcurrentlocationc=f.get (; //printingthecharactercoutcendl; //closing the file F.close (; 返回0; } Output
08e 919 I 20 end :93 saftertheprogramexecutionthefilecontentis,
tellg和seekg