C++ 标准文件的写入读出(ifstream,ofstream)

 
 
注: "<<", 插入器,向流输入数据
      ">>", 析取器,从流输出数据,
 
ifstream和ofstream主要包含在头文件<fstream>中. fstream可对打开的文件进行读写操作
ifstream <===> 硬盘向内存写入文件
ofstream <===> 内存向硬盘写入文件
ofstream out("out.txt");

if(out.is_open())    //is_open()返回真(1),代表打开成功

{

    out<<"HELLO WORLD!"<<endl;

    out.close();

}

在文件out.txt中写入了HELLO WORLD!

 

ifstream in("out.txt");

cha buffer[200];

if(in.is_open())

{

    while(!in.eof())

    {

        in.getline(buffer,100)

        cout<<buffer<<endl;

        out.close();

    }

}
打开文件:
 
 
ofstream out("/root/1.txt"); 
或者 
ofstream out;
out.open("/root/1.txt");
 
写入:
out << "hello, world!!!" << endl;
 
 
关闭文件:
 
 
out.clear(); //为了代码具有移植性和复用性, 这句最好带上,清除标志位.有些系统若不清理可能会出现问题.
out.close();
 
//对于上面两语句的先后问题.取决于文件打开是否成功,若文件打开失败.先clear后再直接close的话状态位还是会出现问题.. 一般逻辑是先close,不管close成功与否,然后clear清楚标志位
 
文件打开状态的判断(状态标识符的验证):
.bad() <===> 读写文件出错, 比如以r打开写入,或者磁盘空间不足, 返回true
.fail() <===> 同上, 且数据格式读取错误也返回true
.eof() <===> 读文件到文件结尾,返回true
.good() <===> 最通用,如果上面任何一个返回true,则返回false.
如果清除上面标志位,则调用.clear()函数
 
实例完整代码:
 
 
 
 
 
#include <iostream>
#include <string>
#include <sstream>
#include <fstream>
 
using namespace std;
#define TO_NUMBER(s, n) (istringstream(s) >> n)    //字符串转换为数值
#define TO_STRING(n) (((ostringstream&)(ostringstream() << n)).str())    //数值转换为字符串
 
int main(int argc, char **argv)
{
    string lines;
    ifstream infile(argv[1]);
    ofstream outfile(argv[2]);
 
    if(!infile.is_open())
    {
        cout<<argv[1]<<"文件打开失败"<<endl;
        return 0;
 
 
    }
 
    if(!outfile.is_open())
    {
        cout<<argv[2]<<"文件打开失败"<<endl;
        return 0;
    }
 
    while(getline(infile,lines))
    {
        if(infile.eof())
        {
            cout<<"文件读取失败"<<endl;
            break;
        }
 
        istringstream strline(lines);
        string tmp_string;
        int i = 1;
 
        strline>>tmp_string;
        string linename = tmp_string;
        while(strline>>tmp_string)
        {
            outfile<<"# "<<i<<" "<<linename<<" "<<i<<" "<<tmp_string<<endl;;
            i++;
        }
        cout<<"total column is: "<<i<<endl;
    }
 
    infile.clear(); //为了代码具有移植性和复用性, 这句最好带上,清除标志位.有些系统若不清理可能会出现问题.
    infile.close();
    outfile.clear(); //为了代码具有移植性和复用性, 这句最好带上,清除标志位.有些系统若不清理可能会出现问题.
    outfile.close();
 
    return 0;
}
 
 
 
 

猜你喜欢

转载自www.cnblogs.com/linux-wang/p/8950238.html