C++文件流讀取

經過運用ofstream和ifstream類去建立對象來進行文件讀寫。ios

使用文件流新建或打開一個文件,並寫入字符串 "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.中的全部數據讀取出來。spa

#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文件解析的應用。code

wav文件解析:orm

#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;
}
相關文章
相關標籤/搜索