文件读取和写入

  1. 从txt 中读取数据
    在测试过程中,为了避免每次手动输入数据,可以将固定的数据存储在txt文件中,每次执行文件时只需从文件中读入固定的数据就行了。
    如果每一个数据本身不含空格,则相邻两个数据之间以若干个空格或者若干行隔开,通过不同的数据类型存入对应的变量中。
    下面举例说明:
    1.1. 读取一个数组
#include <iostream>
#include<fstream>
#include <vector>
using namespace std;

template <typename Type >
void print(vector<Type>& vec)
{
    for (vector<Type>::size_type index = 0; index < vec.size(); index++)
    {
        cout << vec[index] << " ";
    }
    cout << endl;
}

int main()
{
    ifstream input("arr_in.txt");
    int ele;
    vector<int> origArr;
    if (!input) // 检查是否成功打开文件
    {
        cerr << "Fail to open arr_in.txt !" << endl;
        return 1;
    }
    while (!input.eof()) //判断文件结尾
    {
        input >> ele; 
        origArr.push_back(ele);
    }
    input.close();
    print(origArr);
    return 1 ;
}

1.2. 读入不同类型的数据

...
int main()
{
    ifstream input("arr_in.txt");
    int a;
    char c;
    string s;
    if (!input) // 检查是否成功打开文件
    {
        cerr << "Fail to open arr_in.txt !" << endl;
        return 1;
    }
    input >> a >> c >> s;
    input.close();
    cout << a << " "<<c << " "<<s << " "<< endl;
    return 0 ;
}

1.3. 每次读入一行

int main()
{
    vector<string>vec_str;
    ifstream input("arr_in.txt");
    ofstream output("arr_in.txt", ios::app);
    string s;
    if (!input)
    {
        cerr << "Fail to open arr_in.txt !" << endl;
        return 1;
    }
    while (getline(input,s)) //读入一行
    {
        vec_str.push_back(s);
    }
    input.close();
    print(vec_str);
}

2. 向txt中写入数据
写入数据这里简单分为三种:
case1: 直接在现有文件末尾添加数据
case2: 清空原始文件的数据,写入新的数据
case3: 重新生成一个文件,或者现有一个空文件,向其中写入数据
接着 1.1 的内容,先读取文件数据,在写入数据

int main()
{
    ifstream input("arr_in.txt");
    ofstream output("arr_in.txt", ios::app); // case1
    //ofstream output("arr_in.txt"); // case2
    //ofstream output("arr_in_new.txt"); // case3
    int ele;
    vector<int> origArr;
    if (!input)
    {
        cerr << "Fail to open arr_in.txt !" << endl;
        return 1;
    }
    while (!input.eof())
    {
        input >> ele;
        origArr.push_back(ele);
    }
    input.close();
    print(origArr);
    if (!output)
    {
        cerr << "Fail to open arr_in.txt !" << endl;
        return 1;
    }
    output << endl;
    output << " After sorted: " << endl;
    for (vector<int>::size_type index = 0; index < origArr.size(); index++)
    {
        output << origArr[index] << " ";
    }
    output.close();
    return 0;
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值