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;

附:(文件打开模式)

原文地址:https://www.cnblogs.com/zhuyp1015/p/2508272.html