曲径通幽论坛

 找回密码
 立即注册
搜索
查看: 3949|回复: 0
打印 上一主题 下一主题

操作文件--将数据写入文件

[复制链接]

4917

主题

5879

帖子

3万

积分

GROAD

曲径通幽,安觅芳踪。

Rank: 6Rank: 6

积分
34382
跳转到指定楼层
楼主
发表于 2011-7-7 21:21:24 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
要对文件进行读写,必须先把 fstream 库包含到源文件中:
[C++] 纯文本查看 复制代码
#include <fstream>

类似于 iostream 库,fstream 库也定义了一些输入/输出功能,它们主要用于文件。

创建一个 ofstream (output file stream,输出文件流) 类型变量:
[C++] 纯文本查看 复制代码
std::ofstream fileOutput("filename");

上面代码中,fileOutput 型变量与一个特定的文件关联在一起,这个 fileOutput 如同 C 语言中的文件流指针 FILE * 。

接着,可以用 is_open() 或 good() 函数确认这个文件是否已被成功打开,:
if (fileOutput.is_open())if (fileOutput.good())

假设这个文件流已经打开,那么便可以往这个文件流中写入数据:
[C++] 纯文本查看 复制代码
fileOutput << "write some data to this file stream. \n";

通常在写文件时,通常需要在每行输出数据的末位加上一个换行符。

在用完文件后,应该及时的关闭相应文件流,如果 C 语言中的 flcose(fp):
[C++] 纯文本查看 复制代码
fileOutput.close();


测试代码
[C++] 纯文本查看 复制代码
#include <iostream>
#include <fstream>

int main(void)
{
    std::ofstream fileOutput("test.txt");

    
    if (fileOutput.is_open()) {
        fileOutput << "hello file stream. \n";
        fileOutput.close();
    } else 
        std::cout << "file create error. \n";

    return 0;
}

运行输出:
$ ./writedata
$ cat test.txt
hello file stream.
说明
默认情况下,当打开一个已经存在的文件用于输出时,程序将删除该文件的原有内容。有时你可能想追加内容,所以需要改变这种默认的行为。方法是在定义 ofstream 类型变量时多提供一个参数,这个参数标志可以让你定义如何打开那个文件(程序打开文件的默认行为是:如果文件不存在则创建之;如果已经存在,替换之。)。比如可以用 ios:app (app 即 append 的意思)标志用来对文件进行追加,而不是删掉原来内容然后全新输入。

假设上面程序已经生成了 test.txt 文件,且里面的内容为 hello file stream 。现在修改上面程序,然后追加一行字符串:
[C++] 纯文本查看 复制代码
#include <iostream>
#include <fstream>

int main(void)
{
    std::ofstream fileOutput("test.txt", std::ios::app);

    
    if (fileOutput.is_open()) {
        fileOutput << "append something to the second line. \n";
        fileOutput.close();
    } else 
        std::cout << "file create error. \n";

    return 0;
}

运行输出:
$ ./writedata
$ cat test.txt
hello file stream.
append something to the second line.

像 ios::app 的还有两个标志值得注意, ios::nocreate 和 ios::noreplace 。ios::noreate 表示如果不存在,就不要去创建它;ios::noreplace 的含义是,如果文件已经存在,就不要打开它,因为这样会覆盖现有的数据。同时使用多个标志用 '|' 操作符隔开。
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|曲径通幽 ( 琼ICP备11001422号-1|公安备案:46900502000207 )

GMT+8, 2024-5-17 20:39 , Processed in 0.063800 second(s), 23 queries .

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表