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;
}

 

 
 
 
 

转载于:https://www.cnblogs.com/linux-wang/p/8950238.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值