C++文件处理

这篇博客详细介绍了C++中的文件处理,包括文件和流的概念,如何创建顺序文件以及使用ofstream对象进行输出,以及如何从顺序文件读取数据,强调了文件打开模式的使用和文件定位指针的操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近在回顾C++的知识,所以整理了这些博客
1、文件和流
cin对象(标准输入流对象)允许程序从键盘或者其他设备输入数据,cout对象(标准输出流对象)允许将程序数据输出到屏幕或者其他设备。C++中,必须包含头文件< iostream>和< fstream>;

2、创建顺序文件

首先贴一段代码:

// Create a sequential file.
#include <iostream>
#include <string>
#include <fstream> // file stream
#include <cstdlib> // exit function prototype
using namespace std;

int main()
{           
   ofstream outClientFile( "clients.dat", ios::out );
   if ( !outClientFile ) // overloaded ! operator
   {
      cerr << "File could not be opened" << endl;
      exit( 1 );
   } // end if

   cout << "Enter the account, name, and balance." << endl
      << "Enter end-of-file to end input.\n? ";

   int account;
   string name;
   double balance;

   // 读数据,然后存入文件
   while ( cin >> account >> name >> balance )
   {
      outClientFile << account << ' ' << name << ' ' << balance << endl;
      cout << "? ";
   } // end while
} // end main

从项目文件中可以看到多出了一个文件”clients.dat”;用记事本打开会显示从命令行录入的内容;
这里写图片描述

主要通过创建ifstream,ofstream,以及fstream的对象来打开文件。
上述代码主要用于输出(从命令行传向文件),所以创建了一个ofstream对象。有两个参数——文件名和文件打开模式——传递到对象的构造函数中。
对于ofstream对象,文件打开模式可以是:
ios::out ——向一个文件输出数据;(如果原文件有数据,将会被清空,如果原文件不存在,则会先创建一个空的文件)
ios::app ——讲数据输出到文件的结尾,不改变在文件中原有的数据;

ofstream文件还可以这样创建:

ofstream outClientFile;
outClientFile.open("clients.dat",ios::out);

相当于:

ofstream outClientFile("clients.dat");
outClientFile << account << ' ' << name << ' ' << balance << endl;

通过流插入运算符<<和对象outClientFile,向文件中写入一组数据;

3、从顺序文件读取数据

#include <iostream>
#include <fstream> // file stream
#include <iomanip>
#include <string>
#include <cstdlib> // exit function prototype
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值