Chinaunix首页 | 论坛 | 博客
  • 博客访问: 8333113
  • 博文数量: 1413
  • 博客积分: 11128
  • 博客等级: 上将
  • 技术积分: 14685
  • 用 户 组: 普通用户
  • 注册时间: 2006-03-13 10:03
个人简介

follow my heart...

文章分类

全部博文(1413)

文章存档

2013年(1)

2012年(5)

2011年(45)

2010年(176)

2009年(148)

2008年(190)

2007年(293)

2006年(555)

分类: C/C++

2006-06-09 10:03:58

//使用(C++库)fstream读写文件
//simple example
#include
#include
using namespace std;
#ifdef WIN32
#define TEST_FILE "c:\\shi\\aaa.txt"
#else
#define TEST_FILE "/tmp/test.txt"
#endif
void test()
{
    //首先将文件内容写为1234567890
    {
        //fstream sfs;
        //sfs.open(TEST_FILE, ios_base::out);
        //注意,文件是写入方式,会覆盖原来内容
        fstream sfs(TEST_FILE, ios_base::out);
        char buf[] = "1234567890";
        sfs.write(buf, sizeof(buf));
        sfs.close();
    }
        //读取文件内容并输出
    {
        int len;
        char* buf;
        //fstream sfs;
        //sfs.open(TEST_FILE);
        fstream sfs(TEST_FILE);
        //定位到文件末尾
        sfs.seekg (0, ios::end);
        //返回地址,也就相当于获得文件的长度
        len = sfs.tellg();
        //获取完毕之后,将文件指针提到前面
        sfs.seekg (0, ios::beg);
        buf = new char[len];
        sfs.read(buf, len);
        cout << buf << endl;
        delete []buf;
        sfs.close();
    }
}
int main(int argc, char* argv[])
{
    test();
    return 0;
}
阅读(5888) | 评论(3) | 转发(0) |
给主人留下些什么吧!~~

chinaunix网友2010-04-15 22:20:48

very well

chinaunix网友2009-11-18 10:18:46

不错,感谢!!!hello