c++文件的输入输出

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u012142460/article/details/88082478

c++ 文件输入输出

要写入文件,要做以下几步骤
1.创建一个ofstream对象来管理输出流
2.将该对象与特定的文件关联起来
3.像使用cout的方式使用该对象,唯一的区别是:输出将进入文件,而不是屏幕
要完成上述任务,首先应包含头文件fstream,对于大多数实现(但不是全部)来说,包含该文件便自动包括iostream文件。

ofstream fout;

接下来,必须将这个对象与特定的文件关联起来。为此,可以使用open()方法,例如要打开jar.txt文件,则可以这样

fout.open("jar.txt");

可以使用另一个构造函数将这两个步骤两步合并成一步

ofstream fout("jar.txt");

然后,以使用cout的方式使用fout,例如,要将hello world放到文件中,可以这样做

fout << "hello world";

以这种方式打开文件时,相当于新建文件,如果之前有这个文件,文件中内容将会被清空。
读取文件时,做以下几个步骤
1.创建一个ifstream对象来管理输入流,头文件包含在fstream中
2.将该对象与特定的文件关联起来
3.使用类似cin的方式操作该对象

ifstream fin; //创建ifstream对象
fin.open("jar.txt");  //打开一个文件

上述两步也可以合并成一步

ifstream fin("jar.txt");

然后我们就可以像使用cin那样使用fin对象,例如

char ch;
fin >> ch   //从jar.txt中读取一个字节到ch
char buf[80];
fin >> buf; //从jar.txt中读取一个字
fin.getline(buf,80); //从jar.txt中读一行
string line;
getline(fin,line); //read from a file to a string object

使用结束时,可以使用close关闭

fout.close();
fin.close;

我们来看一个简单的例子

#include <iostream>
#include <fstream>
#include <string>

int main()
{
    using namespace std;
    string filename;

    cout << "Enter your file name" << endl;
    cin >> filename;

    ofstream fout (filename.c_str());

    fout << "For your eyes only!\n";
    cout << "Enter your secret number" << endl;

    float secret;
    cin >> secret;

    fout << "your secret number is " << secret << endl;
    fout.close();

    ifstream fin (filename.c_str());
    cout << "Here are the contents of " << filename << endl;
    char ch;
    while (fin.get (ch)) {
        cout << ch;
    }
    cout << "Done" << endl;
    fin.close();


    return 0;

}

输出结果:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/u012142460/article/details/88082478