C++文件处理

C++把文件视为无结构的字节流,所以记录等说法在C++文件中是不存在的。
1.创建顺序访问文件

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

int main()
{
 ofstream outClientFile( "clients.txt",ios::out );

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

 cout << "Enter the account, name, and balance,/n"
   << "Enter end-of-fail to end input./n?";

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

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

 system("pause");

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

                                            文件中添加数据)。数据可以写入文件的任务地方
               
               ios::in                      打开文件以便输入
               ios::out                     打开文件以便输出
               ios::trunc                   删除文件中现有内容(这也是ios::out的默认操作)
               ios::binary                  打开文件以进行二进制(也就是非文本)格式输入或输出

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

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

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

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

2.读取顺序访问文件中的数据
#include <iostream>
#include <fstream>
#include <iomanip>
#include <cstdlib>
using namespace std;

void outputline( int, const char * const, double );

int main()
{
 ifstream inClientFile( "clients.txt", ios::in );

 if ( !inClientFile )
 {
  cout << "File could not be opened/n";
  exit( 1 );
 }

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

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

 while ( inClientFile >> account >> name >> balance )
  outputline( account, name, balance );

 system("pause");

 return 0;
}

void outputline( int acct, const char * const name, double bal )
{
 cout << setiosflags( ios::left ) << setw( 10 ) << acct
   << setw( 13 ) << name << setw(7) << setprecision( 2 )
   << resetiosflags( ios::left )
   << bal << '/n';
}
良好编程习惯:如果文件内容不能修改,文件就只能打开用于输入(用ios::in)。这可以避免不慎改动文

件内容。这是最低访问权限原则的另一个例子。
    每个istream对象有一个get指针,表示文件中下一个输入相同的字节数,每个ostream对象有一个put指针,表示文件中下一个输出相同的字节数。语句
                    inClientFile.sekg(0);
将文件位置指针移到文件开头(位置0),连接inClientFile。seekg的参数通常为long类型的整数。

clntdata.h头文件:

#ifndef CLNTDATA_H
#define CLNTDATA_H

struct clientData
{
 int accountNumber;
 char lastName[ 15 ];
 char fastName[ 15 ];
 double balance;
};

#endif

temple.cpp工程文件

#include <iostream>
#include <fstream>
#include <iomanip>
#include <cstdlib>
#include "clntdata.h"
using namespace std;

int enterChoice();
void textFile( fstream & );
void updateRecord( fstream & );
void newRecord( fstream& );
void deleteRecord( fstream& );
void outputLine( ostream&, const clientData & );
int getAccount( const char * const );

enum Choices{ TEXTFILE = 1, UPDATE, NEW, DELETE, END };

int main()
{
 fstream inOutCredit( "ffff.txt", ios::in | ios::out );

 if ( !inOutCredit )
 {
  cerr << "File could not be opened." << endl;
  exit( 1 );
 }

 int Choice;

 while ( ( Choice = enterChoice() ) != END )
 {
  switch ( Choice )
  {
       case TEXTFILE:
     textFile( inOutCredit );
     break;
    case UPDATE:
     updateRecord( inOutCredit );
     break;
    case NEW:
     newRecord( inOutCredit );
     break;
    case DELETE:
     deleteRecord( inOutCredit );
     break;
    default:
     cerr << "Incorrect choice/n";
     break;
  }
  inOutCredit.close();
 }

 system("pause");

 return 0;
}

int enterChoice()
{
 cout << "/nEnter your Choice" << endl
   << "1 - store a formatted text file of accounts/n"
   << "   called /"print.txt/"for printing/n"
   << "2 - update an account/n"
   << "3 - add a new account/n"
   << "4 - delete an account/n"
   << "5 - end program/n?";

 int menuChoice;
 cin >> menuChoice;
 return menuChoice;
}

void textFile( fstream &readFormFile )
{
 ofstream outPrintFile( "print.txt", ios::out );

 if ( !outPrintFile )
 {
  cerr << "File could not be open/n";
  exit( 1 );
 }

 outPrintFile << setiosflags( ios::left ) << setw( 10 )
           << "Account" << setw( 16 ) << "Last Name" << setw( 11 )
     << "First Name" << resetiosflags ( ios::left )
     << setw( 10 ) << "Balance" << endl;
 readFormFile.seekg( 0 );

 clientData client;
 readFormFile.read( reinterpret_cast< char * >( &client ), sizeof( clientData ) );

 while ( !readFormFile.eof() )
 {
  if ( client.accountNumber != 0 )
   outputLine( outPrintFile, client );

  readFormFile.read( reinterpret_cast< char * >( &client ), sizeof( clientData ) );
 }
}

void updateRecord( fstream &updateFile )
{
 int account = getAccount( "Enter account to update" );

 updateFile.seekg( (account - 1 ) * sizeof( clientData) );

 clientData client;
 updateFile.read( reinterpret_cast< char * >( &client ), sizeof( clientData ) );

 if ( client.accountNumber != 0 )
 {
  outputLine( cout, client );
  cout << "/nEnter charge ( + ) or payment ( - );";
  double transaction;
  cin >> transaction;
  client.balance += transaction;

  outputLine( cout, client );

  updateFile.seekg( ( account - 1) * sizeof( clientData ) );
  updateFile.write( reinterpret_cast< char * >( &client), sizeof( clientData ) );
 }
 else
 {
  cerr << "Account #" << account
    << "has no information." << endl;
 }
}

void newRecord( fstream &insertInFile )
{
 int account = getAccount( "Enter new accout number" );

 insertInFile.seekg( (account - 1 ) * sizeof( clientData ) );

 clientData client;
 insertInFile.read( reinterpret_cast< char * >( &client ), sizeof( clientData ) );

 if ( client.accountNumber == 0 )
 {
  cout << "Enter lastname, firstname, balance/n?";
  cin >> client.lastName >> client.fastName >> client.balance;
  client.accountNumber = account;

  insertInFile.seekp( ( account - 1 ) * sizeof( clientData ) );
  insertInFile.write( reinterpret_cast< char * >( &client ), sizeof( clientData ) );
 }
 else
  cerr << "Account # " << account
       << "already contains information." << endl;
}

void deleteRecord( fstream &deleteFormFile )
{
 int account = getAccount( "Enter to account delete" );

 deleteFormFile.seekg( (account -1 ) * sizeof( clientData ) );

 clientData client;
 deleteFormFile.read( reinterpret_cast< char * >( &client ), sizeof( clientData ) );

 if ( client.accountNumber != 0 )
 {
  clientData blankClient = {0, "", "", 0.0 };

  deleteFormFile.seekp( ( account - 1 ) * sizeof( clientData ) );
  deleteFormFile.write( reinterpret_cast< char *>( &blankClient),sizeof( clientData ) );
  cout << "Account #" << account << "deleted." << endl;
 }
 else
  cout << "Account #" << account << "is Empty" << endl;
}

void outputLine( ostream &output, const clientData &c )
{
 output << setiosflags( ios::left ) << setw( 10 )
  << c.accountNumber << setw( 16 ) << c.lastName
  << setw( 11 ) << c.fastName << setw( 10 )
  << setprecision( 2 ) << resetiosflags( ios::left )
  << setiosflags( ios::fixed | ios::showpoint )
  << c.balance << endl;
}

int getAccount( const char * const prompt )
{
 int account;

 do
 {
  cout << prompt << "(1 - 100):";
  cin >> account;
 }
 while ( account < 1 || account > 100 );

 return account;
}

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值