Chinaunix首页 | 论坛 | 博客
  • 博客访问: 171299
  • 博文数量: 25
  • 博客积分: 3015
  • 博客等级: 中校
  • 技术积分: 545
  • 用 户 组: 普通用户
  • 注册时间: 2007-08-15 17:00
文章分类

全部博文(25)

文章存档

2010年(1)

2009年(9)

2008年(15)

我的朋友

分类: C/C++

2008-05-10 14:23:57


//使用(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;
}

C++ 判断文件是否存在
#include
#include
using namespace std;
#define FILENAME "stat.dat"
int main()
{
 fstream _file;
 _file.open(FILENAME,ios::in);
 if(!_file)
 {
 cout< }
 else
 {
 cout< }
 return 0;
}
阅读(926) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~