C++文件操作


C++用 ifstream 聲明輸入文件對象,用 ofstream 聲明輸出文件對象。

getline的使用:(感覺有點像孔乙己的茴香豆的 茴 的寫法了)

#include<iostream>

#include<fstream>

#include<string>

using namespace std;

int main()

{

    ifstream infile("getline.txt",ios::in | ios::binary);

    char buf1_1[30];

    string buf1;

    char buf2[30];

    ///注意這里getline的兩種不同的函數定義,輸入緩沖一個需要string類型(【1】)

    ///另一個需要char* 類型(【2】)

    getline(cin,buf1); //istream& getline ( istream& is, string& str );  【1】

    cin.getline(buf1_1,30); ///【2】

    /*

    istream& getline (char* s, streamsize n );

    istream& getline (char* s, streamsize n, char delim );

    */

    infile.getline(buf2,30,'a');

    /*

    istream& getline (char* s, streamsize n );

    istream& getline (char* s, streamsize n, char delim );

    //delime表示遇到該字符結束,也可以不使用

    */

    cout << "buf1: "<< buf1 <<endl;

    cout << "buf1_1: "<< buf1_1 <<endl;

    cout << "buf2: "<< buf2 <<endl;

    return 0;

}

 

使用ofstream簡化文件輸出(不用使用fwrtie):

ofstream examplefile ("example.txt");

    if (examplefile.is_open())

     {

        examplefile << "This is a line.\n";  //直接將該字符串寫入到examplefile文件中

        examplefile << "This is another line.\n";

        examplefile.close();

     }

使用ifstream簡化文件輸入(不用使用fread):

char buffer[256];

    ifstream examplefile ("example.txt");

    if (!examplefile.is_open())

    {

        cout << "Error opening file";

        exit (1);//include<stdlib.h>

    }

    while (!examplefile.eof() )

    {

        examplefile.getline (buffer,100);

        cout << buffer << endl;

}

 

使用C++ seek

    const char * filename = "example.txt";

    char * buffer;

    long size;

    ifstream file (filename, ios::in|ios::binary|ios::ate);

    ofstream file_out ("example_out.txt",ios::out | ios :: app);

    //file.seekg (0, ios::end); //因為上面使用了ios::ate 所以這里不用seek end了

    size = file.tellg();//tellg獲取當前讀文件的位置,這里也就是文件大小

    /*

        說明

        獲取或者移動文件制作,對於tellg、seekg 來說是針對ifstream

        對於tellp、seekp來說是針對ofstream

        seekp 或 seekg:

        ios::beg  From beginning of stream

        ios::cur  Current position in stream

        ios::end  From end of stream

    */

    buffer = new char [size + 1];

    file.seekg(0,ios::beg);//在將文件指針移回來以便讀入

    file.read (buffer, size); //istream& read ( char* s, streamsize n );

    buffer[size] = '\0';

    file.close();

    cout << "size: "<<size<<endl;

    cout << "the complete file is in a buffer: "<<endl;

    cout<<buffer<<endl;

    file_out.write(buffer,size);//ostream& write ( const char* s , streamsize n );

    file_out.write(buffer,size);//這里寫了兩次主要是為了證明

                                //file_out是以ios :: app的方式打開的,其看出來實也沒有當你再次運行該程序的時候才能

    delete[] buffer;

 

附:(文件打開模式)

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM