文件操作:洗牌/统计文本文件单词/复制mp3文件/多个文件合并成一个文件

1.将随机洗牌结果保存到文件中

#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
#include <ctime>
using namespace std;
#define SUIT_NUMBER 4
#define FACE_NUMBER 13
class Card{
public:
    string suit;  //花色
    string face;  //面值
};
class CardManager{
private:
    Card deck[SUIT_NUMBER][FACE_NUMBER];
public:
    CardManager()  //构造函数
    {
        string suit[]={"红桃","方块","梅花","黑桃"};
        string face[]={"A","2","3","4","5","6","7","8","9","10","J","Q","K"};
        int i,j;
        for(i=0;i<SUIT_NUMBER;i++)
        {
            for(j=0;j<FACE_NUMBER;j++)
            {
                deck[i][j].suit=suit[i];
                deck[i][j].face=face[j];
            }
        }
    }
    void shuffle()  //洗牌
    {
        srand(time(NULL));
        int i,j;
        for(i=0;i<SUIT_NUMBER;i++)
        {
            for(j=0;j<FACE_NUMBER;j++)
            {
                int m=rand()%SUIT_NUMBER;  //随机选取huase
                int k=rand()%FACE_NUMBER;  //随机选取面值
                Card temp=deck[i][j];  //洗牌的模拟过程(交换)
                deck[i][j]=deck[m][k];
                deck[m][k]=temp;
            }
        }
    }
    void deal()  //发牌
    {
        ofstream out("puke.txt");  //打开文件
        if(!out)  //判断文件打开是否正确
        {
            cout<<"puke.txt文件打开失败!"<<endl;
            return;
        }
        out<<"=============="<<endl;
        out<<"52张牌洗牌结果"<<endl;
        out<<"=============="<<endl;
        string person[]={"甲","乙","丙","丁"};
        int i,j;
        for(i=0;i<SUIT_NUMBER;i++)
        {
            out<<person[i]<<"的牌:"<<endl;
            for(j=0;j<FACE_NUMBER;j++)
            {
                out<<"第"<<j+1<<"张:"<<deck[i][j].suit<<deck[i][j].face<<"\t";
                if((j+1)%4==0)  //每行输出四张牌
                {
                    out<<endl;
                }
            }
            out<<endl<<endl;
        }
        out.close();  //关闭文件
        cout<<"puke.txt文件成功生成,请查阅!"<<endl;
    }
};
int main( )
{
    CardManager cm;  //扑克管理类对象
    cm.shuffle();  //洗牌
    cm.deal(); //发牌
    return 0;
}

运行成功后打开puke.txt文件,如下所示


2.统计文本文件中的单词

#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;
class wordtype{//单词类
public:
    char word[20]; //单词
    int count;  //数量
};
int getwords(wordtype *words);  //获取单词函数的声明
int main( )
{
    string s;
    wordtype words[100]={"",0};//单词对象变量定义和初始化
    int n=getwords(words);  //调用获取单词的函数
    cout<<"英文单词统计结果如下:"<<endl;
    int m;
    for(m=0;m<n;m++)
    {
        cout<<words[m].word<<':'<<words[m].count<<endl;
    }
    cout<<"搜索共"<<n<<"个单词"<<endl;
    return 0;
}
int getwords(wordtype *words)  //获取单词函数的定义
{
    ifstream fin("words.txt");  //打开英文文件
    if(!fin)
    {
        cout<<"文件打开错误"<<endl;
        return 1;
    }
    int n=0;
    char word[20];
    int m;
    while(fin)
    {
        fin>>word;  //读单词
        if(!fin) //文件结尾时退出循环
        {
            break;
        }
        bool flag=false;
        for(m=0;m<n;m++)
        {
            if(!strcmp(word,words[m].word))  //该单词已存在
            {
                words[m].count++;  //原单词计数加1
                flag=true;
                break;
            }
        }
        if(!flag)  //发现新单词
        {
            words[m].count=1;  //新单词计数加1
            strcpy(words[m].word,word);  //保存新单词
            n++;  //总单词数加1
        }
    }
    fin.close();  //关闭文件
    return n;  //返回单词个数
}

运行结果如下,


3.复制一个MP3二进制文件到另一个二进制文件

#include <iostream>
#include <fstream>
using namespace std;
bool mp3cpy(const char *szDestFile,const char *szOrigFile);  //mp3文件复值函数

int main( )
{
    char szOrigFile[50];  //原始文件名
    char szDestFile[50];  //目标文件名
    cout<<"请输入原始文件名和目标文件名:";
    cin>>szOrigFile;
    cin>>szDestFile;
    bool bRet=mp3cpy(szDestFile,szOrigFile);  //调用文件复制函数
    if(bRet)
        cout<<"文件复制成功!"<<endl;
    else
        cout<<"文件复制失败!"<<endl;
    return 0;
}

bool mp3cpy(const char *szDestFile,const char *szOrigFile)  //mp3文件复值函数
{
    ofstream fout(szDestFile,ios::binary);  //以二进制方式打开目标文件
    ifstream fin(szOrigFile,ios::binary);  //以二进制方式打开原始文件
    bool bRet=true;
    if(fin.bad())  //原始文件出错
    {
        bRet=false;
    }
    else
    {
        fin.seekg(0L,ios::beg); //开始位置指向文件开始处
        while(!fin.eof())  //没有指向文件结束
        {
            char szBuf[256]={0};
            fin.read(szBuf,sizeof(char)*256);  //每次读取原始文件最多256个字节
            int length=fin.gcount();  //实际读取的字节数
            if(fout.bad())  //目标文件出错
            {
                bRet=false;
                break;
            }
            fout.write(szBuf,length);  //每次写入目标文件length个字节
        }
    }
    fout.close();  //关闭目标文件
    fin.close();  //关闭源文件
    return bRet;
}

执行结果:

文件复制成功后可以通过播放器打开"布列瑟农.mp3"这首歌,可以对比和原歌曲“Bressanone.mp3”的音质。

4.多个文本文件合并成一个文件

#include <iostream>
#include <fstream>
using namespace std;
class Student{  //学生类
public:
   int no;  //学号
   string name;  //姓名
   string classname;  //班级
   float math;
   float english;
   float computer;
   float average;
};
float getscore(string filename,int stdno);  //读取学生成绩文件函数
ostream &operator<<(ostream& out,Student &student);//重载流操作符
float getscore(string filename,int stdno)
{
    int stdno_temp;
    float score;
    ifstream fin(filename.c_str());  //打开成绩文件
    if(!fin)  //判断文件打开是否正确
    {
        cout<<"文件打开失败"<<endl;
        return 1;
    }
    bool flag=false;
    while(fin)
    {
        fin>>stdno_temp>>score;
        if(fin)//正确读取
        {
            if(stdno_temp==stdno)
            {
                flag=true;
                break;
            }
        }
    }
    if(!flag)
        score=0;
    fin.close();
    return score;
}
ostream &operator<<(ostream& out,Student &student)  //重载流操作符
{
    out<<student.no<<"\t"<<student.name<<"\t"<<student.classname;
    out<<"\t"<<student.math;
    out<<"\t"<<student.english;
    out<<"\t"<<student.computer;
    out<<"\t"<<student.average;
    out<<endl;
    return out;
}
int main( )
{
    ifstream in("info.txt");  //打开学生信息文件
    ofstream out("student.txt");  //打开学生完整信息文件
    if(!in || !out) //打开文件是否成功
    {
        cout<<"文件打开失败"<<endl;
        return 1;
    }
    out<<"学号\t\t姓名\t班级\t高数\t大英\t计算机\t平均"<<endl;
    while(in)
    {
        Student student;
        in>>student.no>>student.name>>student.classname;
        if(!in) //若读取失败则跳出
        {
            break;
        }
        student.math=getscore("math.txt",student.no);
        student.english=getscore("english.txt",student.no);
        student.computer=getscore("computer.txt",student.no);
        student.average=(student.math+student.english+student.computer)/3;
        out<<student;  //写入文件
    }
    out.close();  //关闭文件
    in.close();
    cout<<"student.txt文件建立成功,请查阅!"<<endl;
    return 0;
}

编辑好四个文件:info.txt,math.txt,english.txt,computer.txt


运行成功后,打开student.txt文件如下,



来自西安交通大学MOOC课件


5.考虑到文件的分隔符不同,可以采用以下方式:

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

//读取方式: 逐词读取, 词之间用空格区分
//read data from the file, Word By Word
//when used in this manner, we'll get space-delimited bits of text from the file
//but all of the whitespace that separated words (including newlines) was lost. 
void ReadDataFromFileWBW()
{
    ifstream fin("data.txt");  
    string s;  
    while( fin >> s ) 
    {    
        cout << "Read from file WBW : " << s << endl;  
    }
}

//读取方式: 逐行读取, 将行读入字符数组, 行之间用回车换行区分
//If we were interested in preserving whitespace, 
//we could read the file in Line-By-Line using the I/O getline() function.
void ReadDataFromFileLBLIntoCharArray()
{
    ifstream fin("data.txt"); 
    const int LINE_LENGTH = 100; 
    char str[LINE_LENGTH];  
    while( fin.getline(str,LINE_LENGTH) )
    {    
        cout << "Read from file LBL : " << str << endl;
    }
}

//读取方式: 逐行读取, 将行读入字符串, 行之间用回车换行区分
//If you want to avoid reading into character arrays, 
//you can use the C++ string getline() function to read lines into strings
void ReadDataFromFileLBLIntoString()
{
    ifstream fin("data.txt");  
    string s;  
    while( getline(fin,s) )
    {    
        cout << "Read from file LBL : " << s << endl; 
    }
}

//带错误检测的读取方式
//Simply evaluating an I/O object in a boolean context will return false 
//if any errors have occurred
void ReadDataWithErrChecking()
{
    string filename = "dataFUNNY.txt";  
    ifstream fin( filename.c_str());  
    if( !fin ) 
    {   
        cout << "Error opening " << filename << " for input" << endl;   
        exit(-1);  
    }
}

int main()
{
	cout<<"*********ReadDataFromFileWBW():逐词读入字符串,空格分隔**************"<<endl;
    ReadDataFromFileWBW(); //逐词读入字符串 
    
	cout<<"****ReadDataFromFileLBLIntoCharArray():逐行读入字符串到数组,回车分隔*****"<<endl;
    ReadDataFromFileLBLIntoCharArray(); //逐词读入字符数组
    
	cout<<"*******ReadDataFromFileLBLIntoString():逐行读入字符串,回车换行分隔*********"<<endl;
    ReadDataFromFileLBLIntoString(); 
    
	cout<<"*********ReadDataWithErrChecking():打开文件时带检测功能**************"<<endl;
    ReadDataWithErrChecking(); //带检测的读取
	
    return 0;
}

data.txt文件内容如下,


执行结果:


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值