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

c++中读写文件操作

时间:2017-03-25 22:16:27      阅读:168      评论:0      收藏:0      [点我收藏+]

标签:oat   c语言   author   路径   pen   整数   c++11   c++   ror   

读写文件这个,不常用,每次用的时候都会百度一下,每次写法还都不一样,所有总是记混。今天利用点时间总结下之前工程中用过的。以后就安照这种方法写了。

搞acmicpc的时候喜欢用freopen(),这个是c语言里面的用法如下:

#include<stdio.h>

int main(){
    freopen("in.txt","r",stdin);
    freopen("out.txt","w",stdout);
    int n,m;
    while(cin>>n>>m){
        cout<<n+m<<endl;
    }
    return 0;
}

这样,从in.txt中读进来多组n,m 然后计算n+m再写入out.txt中,每次写入都会把之前out.txt中的数据清空。

因为,现在实习总写c++.下面说一下c++文件的读取写入操作。

文件读取写入的类库是fstream,更具体的说读取时 ifstream 写入是 ofstream

例子:

/* ***********************************************
Author        :guanjun
Created Time  :2017/3/18 13:32:52
File Name     :33.cpp
************************************************ */
#include <bits/stdc++.h>
//#include <fstream>
using namespace std;

int main(){
    ofstream out("d://out2.txt");//初始化一个out对象
    if(!out){                    //是否正常打开
        cout<<"error";  
    }
    else{
        out<<"1234";              //写入数据   
    }
    out.close();                  //关闭
    return 0;
}

哎,c++11用一个<bits/stdc++.h>就可以把所有头文件都包括进来了。以上是在windows下的。linux路径格式会有区别。

有些时候,我们并不希望第二次写入的时候,之前的数据被清空。这时我们可以这么写。

例子:

/* ***********************************************
Author        :guanjun
Created Time  :2017/3/18 13:32:52
File Name     :33.cpp
************************************************ */
#include <bits/stdc++.h>
//#include <fstream>
using namespace std;

int main(){
    ofstream out("d://out2.txt",ios::out|ios::app);
    if(!out){
        cout<<"error";
    }
    else{
        out<<"5";
    }
    out.close();
    return 0;
}

其实当 ofstream创建对象 out的时候默认ios::out,如果想用追加的方式打开的话,可以在后面加上|ios::app,像 ios::app这样的参数有很多,比如ios::binary等。 | 是或的意思。

文件读入的例子:按字符串读取,空格和换行作为分割,读到文件末尾

#include <bits/stdc++.h>
//#include <fstream>
using namespace std;

int main(){
    ifstream in("d://out2.txt");
    if(!in){
        cout<<"error";
    }
    else{
        string s;//如果是以确定类型,这块也可以改成 int,float等
        while(in>>s){
            cout<<s<<endl;
        }
    }
    in.close();
    return 0;
}

也可以这样,按行读取成字符串,分隔符是换行

#include <bits/stdc++.h>
//#include <fstream>
using namespace std;

int main(){
    ifstream in("d://out2.txt");
    if(!in){
        cout<<"error";
    }
    else{
        string s;
        while(getline(in,s)){
            cout<<s<<endl;
        }
    }
    in.close();
    return 0;
}

 

关于文件写入,读出其实还有很多内容,可以参考 《C++ Primer Plus  第6版  中文版》

关于cin,cout其实有

这里用一个很妙的技巧。

如何把整数装换成字符串?可以利用ostringstream啊!

ostringstream os;
os<<123;
string s="0"+os.str();
cout<<s<<endl;

输出0123

 

c++中读写文件操作

标签:oat   c语言   author   路径   pen   整数   c++11   c++   ror   

原文地址:http://www.cnblogs.com/pk28/p/6618748.html

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