练习:C++ 文件操作 例程

#include<iostream>
#include
<string.h>

using namespace std; //申明命名空间

//error()函数
void error()
{
cout
<<"/nCan not open the file."<<endl;
exit(
1);//退出
}

int main(void)
{
FILE
*fp;//定义一个文件指针
char str[80];

cout
<< "Input:";//从键盘读取输入
cin.getline(str,80);

if( (fp=fopen("test.dat","w")) == NULL) //新建一个test.dat文件
error();

fputs(str,fp);
//write the str to fp;
fputs("\n",fp);
fclose(fp);
//Close the file;

if((fp=fopen("test.dat","r"))==NULL)
error();

char ch;
cout
<<"Output:";
while( (ch=fgetc(fp)) != EOF)
cout
<< ch;
fclose(fp);
}

一个十分简单的例程.

posted @ 2011-08-12 21:55  hnrainll  阅读(592)  评论(0编辑  收藏  举报