• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
Linux-wang
博客园    首页    新随笔    联系   管理    订阅  订阅
C++ 标准文件的写入读出(ifstream,ofstream)
ttp://blog.csdn.net/a125930123/article/details/53542261
 

 

 
注: "<<", 插入器,向流输入数据
      ">>", 析取器,从流输出数据,
 
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;
}

 

 
 
 
 
posted on 2018-04-26 11:01  SmallMosquito  阅读(16950)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3