转载:http://bbs.shudoo.com/viewthread.php?tid=1657415 //高手请路过。= =。纯粹练习专用,欢迎盗版。 #include <fstream> #include <string> using namespace std; int main() { string path = "C://CData.lct"; fstream TestFile; TestFile.open(path.c_str()); if(!TestFile) { //不存在文件 cout<<"File not exist, program will create it./n"; TestFile.open(path.c_str(),ios::out); } cout<<"New position: "<<TestFile.tellp()<<endl;//目前位置 //写文件 TestFile.seekp(0); string str_My_say = "Here is leap-ahead"; TestFile.write(str_My_say.c_str(),sizeof(str_My_say)); cout<<"New position: "<<TestFile.tellp()<<endl; //读文件 TestFile.seekg(ios::beg);//回到文件头 char temChar; TestFile.get(temChar); cout<<"Read a char: "<< temChar<<endl; cout<<"New position: "<<TestFile.tellp()<<endl; TestFile.seekg(ios::beg); string temStr((std::istreambuf_iterator<char>(TestFile)),std::istreambuf_iterator<char>()); //全文读入string cout<<"Read some chars: "<<temStr.c_str()<<endl; cout<<"New position: "<<TestFile.tellp()<<endl; //ignore 演示 TestFile.seekg(ios::beg); TestFile.ignore(5,'e'); TestFile.get(temChar); cout<<"Ignore some chars and get next char: " <<temChar<<endl; cout<<"New position: "<<TestFile.tellp()<<endl; system("pause"); }