fstream--文本数据迁移

C++文件读写示例
本文介绍了一个使用C++进行文件读写的示例程序。该程序通过ifstream和ofstream类从一个文件读取数据并将其写入另一个文件,展示了基本的文件操作方法。
 1 // ifile_ofile_test.cpp : 定义控制台应用程序的入口点。
 2 //
 3 
 4 #include "stdafx.h"
 5 
 6 #include <stdio.h>
 7 #include <stdlib.h>
 8 
 9 #include <iostream>
10 #include <fstream>
11 #include <string>
12 
13 int move_data(const std::string _ifilename, const std::string _ofilename)
14 {
15     char cVal[8] = {0};
16     std::string line;
17     try
18     {
19         std::ifstream ifile(_ifilename.c_str(),std::ios::in);//只读方式读取文件
20         std::ofstream ofile(_ofilename.c_str(), std::ios::out|std::ios::app);//输出到新文件中
21 
22         if (ifile.fail())
23         {
24             std::cout<<"Unable to init ifstream file"<<std::endl;
25         }
26         if (ofile.fail())
27         {
28             std::cout<<"Unable to init ofstream file"<<std::endl;
29         }
30         else if (ifile.is_open()&&ofile.is_open())
31         {
32             /*读数据*/
33             while(getline(ifile, line))
34             {
35                 ofile << line<<std::endl;
36             }
37             ifile.close();
38             ofile.close();
39             return 0;
40         }
41         else
42         {
43             std::cout<<"error"<<std::endl;
44         }
45     }
46     catch (std::exception& exc)
47     {
48         std::cout<<"error:"<<exc.what()<<std::endl;
49     }
50 
51     return 0;
52 }
53 int _tmain(int argc, _TCHAR* argv[])
54 {
55     std::string ifilename="http://www.cnblogs.com/infile.txt";
56     std::string ofilename="http://www.cnblogs.com/outfile.txt";
57     if(move_data(ifilename,ofilename)==0)
58     {
59         std::cout<<"迁移数据成功"<<std::endl;
60     }
61     return 0;
62 }

 

转载于:https://www.cnblogs.com/huanghuang/archive/2012/12/27/2836030.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值