码迷,mamicode.com
首页 > 编程语言 > 详细

C++ 文件流操作必知必会

时间:2017-04-06 12:33:05      阅读:206      评论:0      收藏:0      [点我收藏+]

标签:二进制   lan   this   names   常用   文件流   opera   ring   情况   

一、文件流操作

  1.确定文件打开的模式。可以选的模式主要有:

ios::in 为输入(读)而打开一个文件
ios::out 为输出(写)而打开文件 
ios::ate 初始位置:文件尾 
ios::app 所有输出附加在文件末尾 
ios::trunc 如果文件已存在则先删除该文件 
ios::binary 二进制方式

  2.默认情况下是以文本的方式写文件,并且会删除原本文件中的数据,即ios::trunc

  3.判断文件是否正常打开。好的文件操作习惯是,每次打开一个文件后,在进行文件写之前要判断文件是否正常打开,使用的函数是is_open()

  4.文件写。主要有下面三函数,<< 流操作符,写一个字符put(),写一块数据write;

std::ostream::operator<<
std::ostream::put
std::ostream::write

5.文件读。主要有流操作符>>,读一个字符get,读一行getline,读文件中一块read

std::istream::operator>>
istream& operator>> (int& val);
std::istream::getline
istream& getline (char* s, streamsize n );
istream& getline (char* s, streamsize n, char delim );
std::getline (string)
istream& getline (istream& is, string& str, char delim);
istream& getline (istream& is, string& str);
std::istream::read
istream& read (char* s, streamsize n);
std::istream::get
istream& get (char& c);

6.文件结尾的判断 infile.eof()

7.文件关闭 infile.close()

8.文件定位 seekp(),seekg()

9.文件修改,见实例

1.1 文件写

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

using namespace std;
int main() {
    /*
     * ios::app:添加,ios::trunc:如果文件存在,先删除该文件(默认)
     * bios::binary 二进制方式读写,默认是文本方式
     */
    ofstream outfile("testfile.txt",ios::out | ios::trunc);
    if(!outfile.is_open()){
        cerr << "file cannot open!" << endl;
        return -1;
    }

    outfile << "This is a test.\n";
    outfile << 100 << endl;

    outfile.put(c);  // write a char.
    outfile.put(\n);

    char buffer[1024] = "abc";
    outfile.write(buffer,sizeof(buffer)); // write a block.

    outfile.close();

    return 0;
}

1.2 文件读

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

using namespace std;
int main() {

    ifstream infile("testfile.txt");
    if (!infile.is_open()) {
        cerr << "file cannot open!" << endl;
        return -1;
    }

    //读一个字符
    char ch;
    infile.get(ch);

    //读一个字符串
    string word;
    infile >> word;

    //读一行 常用
    infile.seekg(0);
    string line;
    getline(infile, line);

    char buffer[1024];
    infile.seekg(0); //定位到文件头
    infile.getline(buffer, sizeof(buffer));
    
    //读文件块
    infile.seekg(0);
    infile.read(buffer, sizeof(buffer));

    //判断文件结尾
    infile.seekg(0);
    while (!infile.eof()) {
        getline(infile,line);
//        infile >> word;
//        infile.read(buffer,sizeof(buffer));
    }

    infile.close();
    return 0;
}

 1.3 文件内容修改

#include <fstream>

using namespace std;
int main() {
    fstream inOutFile("testfile.txt",ios::in | ios::out);
    inOutFile.seekg(50);
    inOutFile << "修改文件很容易!\n";
    inOutFile.close();
    return 0;
}

 

C++ 文件流操作必知必会

标签:二进制   lan   this   names   常用   文件流   opera   ring   情况   

原文地址:http://www.cnblogs.com/wxquare/p/6670562.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!