zoukankan      html  css  js  c++  java
  • C++文件流读取

    通过运用ofstream和ifstream类去创建对象来进行文件读写。

    使用文件流新建或打开一个文件,并写入字符串 "This is a test file".

    #include<fstream>
    #include<iostream>
    using namespace std;
    int main()
    {
        ofstream outFile("test.txt",ios::out);
    
        if(!outFile)
            cout<<"Open file or create file error."<<endl;
        else
            outFile<<"This is a file."<<5<<" "<<1.2;
        return 0;
    }

    使用文件流将创建的文件test.txt.中的所有数据读取出来。

    #include<fstream>
    #include<iostream>
    using namespace std;
    int main()
    {
        ifstream inFile("test.txt",ios::in);
        int b;
        char a[100];
        float c;
    
        if(!inFile)
            cout<<"File open error."<<endl;
        else
        {
            inFile>>a;
            in
            cout<<"string--"<<a<<endl;
            cout<<"int--"<<b<<endl;
            cout<<"float--"<<c<<endl;
        }
        return 0;
    }

    使用ifstream类成员函数seekg,结合文件输入输出流,写的一个wav文件解析的应用。

    wav文件解析:

    #include<fstream>
    #include<iostream>
    #include<cstring>
    //#incl
    #define MAX_STR_LEN 32
    using namespace std;
    class wav
    {
        public:
                 char id[4];
        unsigned long file_size;
          //文件大小
        unsigned short channel;            //通道数
        unsigned int frequency;        //采样频率
        unsigned long Bps;                //Byte率
        unsigned short sample_num_bit;    //一个样本的位数
        unsigned long data_size;        //数据大小
        unsigned char *data;            //音频数据 ,这里要定义什么就看样本位数了,我这里只是单纯的复制数据
    };
    int main()
    {
        wav ww;
    
        ifstream inFile("do.wav",ios::in|ios::binary);
        if(!inFile)
            cout<<"error";
        else{
        char buff[4];
        unsigned long tlong ;
        unsigned short tshort;
    
        inFile.seekg(0,ios::beg);
        inFile>>ww.id;
    
        inFile.seekg(12,ios::beg);
        inFile>>buff;
        cout<<"fmt:"<<buff<<endl;
    
        inFile.seekg(16,ios::beg);
        inFile>>buff;
        memcpy(&tlong,buff,sizeof(unsigned long));
        cout<<"fmt size:"<<tlong<<endl;
    
        inFile.seekg(20,ios::beg);
        inFile>>buff;
        memcpy(&tshort,buff,sizeof(unsigned short));
        cout<<"format:"<<tshort<<endl;
    
        inFile.seekg(4,ios::beg);
        inFile>>ww.file_size;
        inFile.seekg(22,ios::beg);
        inFile>>ww.channel;
        inFile.seekg(24,ios::beg);
        cout<<ww.id<<endl<<ww.file_size<<endl<<ww.channel<<endl<<ww.frequency;
        }
        return 0;
    }
  • 相关阅读:
    poj 2312 Battle City
    poj 2002 Squares
    poj 3641 Pseudoprime numbers
    poj 3580 SuperMemo
    poj 3281 Dining
    poj 3259 Wormholes
    poj 3080 Blue Jeans
    poj 3070 Fibonacci
    poj 2887 Big String
    poj 2631 Roads in the North
  • 原文地址:https://www.cnblogs.com/ZP-Better/p/7079157.html
Copyright © 2011-2022 走看看