C++文本文件的读与写

1. 写文本操作 ofstream outFile;

——学习把字符串、int、double类型写到文件中。
代码实现:

/*
_0.cpp 学习总结 视频学习C++_Primer_Plus_6_7
1. outFile.open(),outFile.close()的使用
	outFile.open()打开文件,没有该文件会自动创建该文件
	因此不必判断该文件是否打开
2. 写操作:outFile << 数据; 类比cout操作,cout能操作的outFile也适用
3. 每次写数据(覆盖)
4. 浮点数精度控制问题
*/
#include <iostream>
#include <fstream>//支持文件输入输出

int main()
{
	using namespace std;//最好局部,不要全局

	//汽车名字,年份,原价,现价
	char automobile[60];
	int year;
	double a_price;
	double d_price;
	
	//写文本操作
	ofstream outFile;
	outFile.open("carinfo.txt");//没有会自动创建该文件
	
	//键盘输入
	cin.getline(automobile, 50);
	cin >> year;
	cin >> a_price;
	d_price = 0.913 * a_price;
	
	//屏幕显示信息
	cout << fixed;//不用科学计数法显示
	cout.precision(2);//精度保留两位小数
	cout.setf(ios_base::showpoint);//显示小数点,不写(输入135.0,显示135)
	cout << "automoble: " << automobile << endl;
	cout << "year: " << year << endl;
	cout << "a_price: " << a_price << endl;
	cout << "d_price: " << d_price << endl;
	
	//数据写道文本中
	outFile << fixed;//不用科学计数法显示
	outFile.precision(2);//精度保留两位小数
	outFile.setf(ios_base::showpoint);//显示小数点,不写(输入135.0,显示135)
	outFile << "automoble: " << automobile << endl;
	outFile << "year: " << year << endl;
	outFile << "a_price: " << a_price << endl;
	outFile << "d_price: " << d_price << endl;
	
	outFile.close();
	return 0;

}

——思考:如何把结构体写入到文本文件中(未解决)。

2. 读取文本操作 ifstream inFile;

——从文本文件中读double类型。
代码实现:

/*
_1.cpp 学习总结 视频学习C++_Primer_Plus_6_8
1. inFile.open(),inFile.is_open(),inFile.close(),inFile.good(),inFile.eof(),inFile.fail()的使用
	inFile.open()打开文件,不会自动创建该文件
	因此需要判断该文件是否打开
2. 读操作:inFile << 数据; 类比cin操作
*/
#include <iostream>
#include <fstream>//支持文件输入输出
#include <cstdlib>//支持exit(EXIT_FAILURE)
const int SIZE = 60;
int main()
{
    using namespace std;
    
    //文本名字
    char filename[SIZE];
    //输入文本名字
    cin.getline(filename, SIZE);
    cout << "filename: " << filename << endl;

    //读文本操作
    ifstream inFile;
    inFile.open(filename);//读操作不能自动创建文件
    if(!inFile.is_open())//!一定不能少
    {
        cout << "打不开这个文件夹: " << filename << endl;
        exit(EXIT_FAILURE);
    }
    
    double value;
    double sum = 0;
    int count = 0;

    //读double类型
    inFile >> value;
    while(inFile.good())//判断读取的数据是否为double类型
    {
        ++count;
        sum += value;
        inFile >> value;
    }

    if(inFile.eof())
        cout << "已读到文件末尾" << endl;
    else if(inFile.fail())
        cout << "读到了一个错误数据,提前跳出循环" << endl;
    
    if(count == 0)
        cout << "没有数据可读" << endl;
    else
    {
        cout << "Items read: " << count << endl;
        cout << "Sum: " << sum << endl;
        cout << "Average: " << sum / count << endl;
    }

    inFile.close();
    return 0;
}

3. 向文件末尾追加内容 ofstream fout(file, ios::out | ios::app);

——向文件末尾追加内容 。
代码实现:

/*
_3.cpp 学习总结 视频学习C++_Primer_Plus_17_6
1. ofstream fout(file, ios::out | ios::app);
    等价于ofstream fout;fout.open(file, ios::out | ios::app);
2. fin.clear();//二次打开文件要清除上次打开的痕迹(流)
3. 写操作打开文件后不用判断是否打开文件,因为没有该文件会自动创建
*/
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>

const char *filename = "guests.txt";
int main()
{
    using namespace std;
    char ch;

    //读操作
    ifstream fin;
    fin.open(filename);//打开guests.txt,存顾客的名字(已存在)
    if(!fin.is_open())
    {
        cout << "打不开该文件夹:" << filename << endl; 
        exit(EXIT_FAILURE);  
    }

    cout << "开始读取当前文件内容:" << endl;
    while(fin.get(ch))
        cout << ch;
    fin.close();

    //写操作
    ofstream fout(filename, ios_base::out | ios_base::app);
    //接下来不用判断是否打开文件,因为没有该文件会自动创建
    //往filename里面继续写名字,追加写
    string name;
    while(getline(cin, name) && name.size() > 0)
        fout << name <<endl;
    fout.close();

    fin.clear();//二次打开文件要清除上次打开的痕迹(流)
    fin.open(filename);
    if(!fin.is_open())
    {
        cout << "打不开该文件夹:" << filename << endl; 
        exit(EXIT_FAILURE); 
    }
    cout << "再次显示filename文件夹中的所有内容" << endl;
    while(fin.get(ch))
        cout << ch;
        
    fin.close();
    return 0;
}

4. 知识点。

常量含义
ios_base::in打开文件,以便读取
ios_base::out打开文件
ios_base::out打开文件,以便写入
ios_base::app追加到文件末尾
ios_base::trunc如果文件存在,清空文件内容
ios_base::binary二进制文件
C++模式C模式含义
ios_base::in“r”打开文件,以便读取
ios_base::out“w”等价于ios_base::out | ios_base::trunc
ios_base::out | ios_base::trunc“w”打开以写入,如果文件存在,先清空文件
ios_base::out | ios_base::app“a”打开以写入,只追加
ios_base::in | ios_base::out“r+”打开以读写,在文件允许的位置写入
ios_base::in | ios_base::out | ios_base::trunc“w+”打开以读写,如果文件按存在,清空文件

5. 小练习。

——p1. 编写一个程序,它打开一个文本文件,逐个字符地读取该文件,直到到达文件末尾,然后输出该文件中包含多少个字符。
代码实现:

//1. inFile >> ch;不接受空格和换行符,遇到自动跳过
#include <iostream>
#include <fstream>
#include <cstdlib>
const int SIZE = 60;
int main()
{
    using namespace std;

    string filename;
    getline(cin, filename);//string 用getline

    ifstream inFile;
    inFile.open(filename);//该文件要存在,否则打开失败
    if(!inFile.is_open())
    {
        cout << "打不开此文件:"  << filename << endl;
        exit(EXIT_FAILURE);
    }

    char ch;
    int count = 0;

    while(!inFile.eof())//不需要提前判断得到的是否为字符
    {
        inFile >> ch;
        count++;
    }

    cout << "Count: " << count << endl;

    inFile.close();
    return 0;
}

——p2.从文件中读取所需要的信息。该文件第一行为捐款人数,余下成对,一行代表姓名,一行代表捐款金额。

	4
	Sam Stone
	2000
	Name: Freida Flass
	100500
	Tammy Tubbs
	Rich Raptor
	55000</font>

代码实现:

/*
1. get()、getline()函数的考察
    getline()与回车结束,并吃掉该回车
    get()吃掉一个字符
2. 指针、new,detele的考察(当然可以选择直接输出,不存储)
*/
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>

using namespace std;

struct patrons
{
    string name;
    int donation;
};

int main()
{
    string filename;
    getline(cin, filename);

    ifstream inFile;
    inFile.open(filename);
    
    if(!inFile.is_open())
    {
        cout << "打不开该文件:" << endl;
        exit(EXIT_FAILURE);
    }

    int num;
    inFile >> num;
    cout << num << endl;
    if(num <= 0)
        exit(EXIT_FAILURE);
    
    int i = 0;
    patrons *ppatrons;//创建一个指针变量,该变量指向结构体的地址
    ppatrons = new patrons[num];//创建按一个patrons类型的数组,
                                //该指针指向该数组的首地址,某种意义上ppations就是该数组的名字
                                //patrons并不是数组的名字

    inFile.get();//吸收文本中整数后面的的回车
    while (!inFile.eof() && i < num)
    {
        getline(inFile, ((ppatrons + i)->name));//遇到回车结束,并吃掉该回车
        inFile >> (ppatrons + i)->donation;
        inFile.get();//吸收文本中整数后面的的回车
        i++;
    }

    for(int i = 0; i < num; i++)
    {
        cout << "Name: " << ppatrons[i].name << endl;
        cout << "Donation: " << ppatrons[i].donation << endl;
    }

    delete []ppatrons;//这么删除才对,不太能理解
    inFile.close();
    return 0;
}
  • 4
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值