当前位置:首页>网络学院>程序开发>Visual C++教程>文章内容

C++中文件处理函数方法分析及实例

[ 来源:http://www.it55.com | 作者: | 时间:2007-09-11 | 收藏 | 推荐 ] 【

先纠正一个错误的理解:C++将文件看作无结构的字节流,也就是说“记录”等说法在C++文件中是错误的。 it55.com

1.创建顺序访问文件 免费资源http://www.it55.com

#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;

免费设计素材下载http://www.it55.com

int main()
{
 ofstream outClientFile( "clients.txt",ios::out ); 免费资源http://www.it55.com

 if ( !outClientFile )
 {
  cerr << "File could not be opened" << endl;         /*测试文件是否打开*/
  exit( 1 );
 } http://www.it55.com

 cout << "Enter the account, name, and balance,\n"
   << "Enter end-of-fail to end input.\n?"; 免费壁纸下载http://www.it55.com

 int account;
 char name[ 30 ];
 double balance;

免费资源http://www.it55.com

 while ( cin >> account >> name >> balance )
 {
  outClientFile << account << " " <<  name << " " << balance << '\n';
  cout << "?";
 }

sflj http://www.it55.com kg^&fgd

 system("pause");

http://www.it55.com/

 return 0;
}
创建流ifstream,ofstream或fstream对象后便打开了文件。
下面列出了文件打开方式:
               文件打开方式                 描述
               ios::app                     将所有输出写入文件末尾
               ios::ate                     打开文件以便输出,并移到文件末尾(通常用于在     

sflj http://www.it55.com kg^&fgd

                                            文件中添加数据)。数据可以写入文件的任务地方
               
               ios::in                      打开文件以便输入
               ios::out                     打开文件以便输出
               ios::trunc                   删除文件中现有内容(这也是ios::out的默认操作)

免费网页模版下载http://www.it55.com

               ios::binary                  打开文件以进行二进制(也就是非文本)格式输入或输出 http://www.it55.com在线教程

常见编程错误:打开一个用户想保留数据的现有文件进行输出(以ios::out方式)。这种操作会在不给出任

精美商业网页模版下载http://www.it55.com

何警告消息的情况下删除文件内容。
常见编程错误:用错误的ofstream对象指定文件。
     可以生成obtream对象但不打开特定文件,可以在后期关联文件与对象。例如声明
                ofstream outClientFiel;
     生成ofstream对象ourClientFile。ofstream成员函数open
                outClientFile.open("clients.txt",ios::out);
     打开文件并将其与现有ofstream对象关联。
常见编程错误:在引用文件之前忘记打开文件。

vd;k;l http://www.it55.com rdfg

性能提示:程序不再引用的文件应立即显式关闭,这样可以减少程序在不再需要特定文件之后继续执行所

免费壁纸下载http://www.it55.com

占用的资源。这种方法还可以使程序更清晰。

免费矢量图片素材下载http://www.it55.com

2.读取顺序访问文件中的数据
#include <iostream>
#include <fstream>
#include <iomanip>
#include <cstdlib>
using namespace std; 精美商业网页模版下载http://www.it55.com

void outputline( int, const char * const, double ); 精美韩国模版下载http://www.it55.com

int main()
{
 ifstream inClientFile( "clients.txt", ios::in ); 免费壁纸下载http://www.it55.com

 if ( !inClientFile )
 {
  cout << "File could not be opened\n";
  exit( 1 );
 } it55.com

 int account;
 char name[ 30 ];
 double balance;

45398 http://www.it55.com it55学习IT知识,享受IT生活 4dfkjn

 cout << setiosflags( ios::left ) << setw( 10 ) << "Account"
   << setw( 13 ) << "Name" << "Balance\n"
   << setiosflags( ios::fixed | ios::showpoint );

(编辑:IT资讯之家 www.it55.com

返回顶部
共3页: 上一页 1 [2] [3] 下一页  

网友评论

[以下评论为网友观点,不代表本站。请自觉遵守互联网相关政策法规,所有连带责任均有评论者自负。]
[不超过250字]