C++文件I/O示例

类别:编程语言 点击:0 评论:0 推荐:

文章标题:C
原 作 者:querw
原 出 处:www.vczx.com
发 布 者:querw
发布类型:原创
发布日期:2004-10-05
今日浏览:8
总 浏 览:144

// 国庆没事写着玩的,英文很烂,请把注意力集中在代码上,呵呵:)

// c++基于流的文件操作使很多C转过来的程序员在操作文件时还是选择了 FILE*

// :)其实,C++的流操作文件也很方便啊

// 下面这个例子就是文件使用实例代码

#pragma warning(disable:4786)
#include <IOSTREAM>
#include <FSTREAM>
#include <string>
using namespace std;
int main()
{
// using std::cout;
// using std::endl;
cout<<" ********************* C ++ file opration demo ***********************"<<endl;
cout<<"using fstream or ifstream and ofstream"<<endl;
cout<<"fstream derive from istream and ostream, so most of method were defined in"<<endl;
cout<<"istream and ostream"<<endl;
cout<<"By the way, I like C style \"FILE *\" indeed. :)"<<endl;

// Input file demo
cout<<endl;
cout<<"****Part 1: Input file demo****"<<endl;

fstream /*ifstream*/ infile;
// antoher way to declare special class or function in a namespace
using std::string;
string strfilename;
cout<<"Input In FileName:"<<endl;
cin>>strfilename;
infile.open(strfilename.c_str(),ios::in/*openmode*/);

// succeed?
if(!infile)
{
 cout<<"Cannot open file:"<<strfilename<<endl;
 return 1;
}

// read a byte
char ch1,ch2;
infile.get(ch1);
ch2 = infile.get();

// read a line
// get(char *,int max_size,char dimiliter) can do the same word as getline()
// but get() doesn't drop the dimiliter,
// use ignore() to drop the dimiliter(the last byte,'\n' by default)

char pszLine[1024];
memset(pszLine,0,1024);
infile.getline(pszLine,1024/*read count*/,'\n'/*read until reach '\n'*/);

// seek function
// seekg means seek for getting use for input file
infile.seekg(0/*offsize*/,ios_base::beg/*seek from ios_base::beg ios_base::cur ios_base::end*/);

// read to a buffer
infile.read(pszLine,1024);

// get readed size
int nReadedSize = infile.gcount();

// tell the position also tellg() and tellp()
// tellg() before read() and tellg() after read() then you can get the readed size
// return -1 if eof() turn true
int nCurPos = infile.tellg();

// test end ?
if(infile.eof())
{
 cout<<"input file reach file end"<<endl;
}

infile.close();

// output file demo
cout<<"****Part 2: Output file demo *****"<<endl;

fstream /*ofstream */outfile;
outfile.open("out.txt",ios::out);
if(!outfile)
{
 cout<<"Cannot open out file out.txt."<<endl;
 return 1;
}

// write a byte
char chout = 'a';
outfile.put(chout);

// write buffer
outfile.write(pszLine,strlen(pszLine));

// like ifstream ,seekp(),tellp()
outfile.seekp(10,ios_base::beg);
char buffer[] = "seekp and write a buffer";
outfile.write(buffer,strlen(buffer));

nCurPos = outfile.tellp();



outfile.close();

return 0;
}

本文地址:http://com.8s8s.com/it/it26790.htm