fstream的基本用法

#include <iostream>
#include <fstream>

using namespace std;

int main(){
    ifstream in;
    in.open("test.txt");
    if(!in){
        cout << "open file failed" << endl;
        return 0;
    }
    char x;

    while(in >> x){
        cout << x;
    }
    cout << endl;
    //--------------------
    ofstream out;
    out.open("test1.txt");
    if(!out){
        cout << "open file failed" << endl;
        return 0;
    }


    for(int i = 0; i < 10; i++){
        out << i;
    }
    cout << endl;
    out.close();

    return 0;
} 

这里写图片描述

常见的打开模式:
ios::in–打开一个可读取文件
ios::out–打开一个可写入文件
ios:binary –以二进制的形式打开一个文件。
ios::app –写入的所有数据将被追加到文件的末尾
ios::trunk –删除文件原来已存在的内容
ios::nocreate –如果要打开的文件并不存在,那么以此叁数调用open函数将无法进行。
ios:noreplece –如果要打开的文件已存在,试图用open函数打开时将返回一个错误。

#include <iostream>
#include <fstream>

using namespace std;

int main(){
    fstream fp("test.txt",ios::in | ios::out);
    if(!fp){
        cout << "open file failed" << endl;
        return 0;
    }
    fp << "WelcomeToMyHome!";
    static char str[100];
    fp.seekg(ios::beg);//使文件指针指向文件头 
    fp >> str;
    cout << str << endl;
    fp.close();
    return 0;
} 

这里写图片描述

  • 19
    点赞
  • 76
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
C++中的 `fstream` 类提供了文件输入/输出的功能,它是 `ifstream` 和 `ofstream` 类的基类,同时具有它们的功能。以下是 `fstream` 的基本用法: 1. 打开文件:可以使用 `open()` 函数打开一个文件,需要提供文件名和打开模式。例如,要以写入模式打开一个名为 `example.txt` 的文件,可以使用以下代码: ```cpp #include <fstream> std::fstream file; file.open("example.txt", std::ios::out); ``` 在上述代码中,`std::ios::out` 表示以写入模式打开文件。 2. 写入文件:可以使用 `<<` 运算符向文件中写入数据,例如: ```cpp file << "Hello World!" << std::endl; ``` 在上述代码中,`std::endl` 表示换行符。 3. 读取文件:可以使用 `>>` 运算符从文件中读取数据,例如: ```cpp std::string data; file >> data; ``` 在上述代码中,`data` 变量将存储从文件中读取的数据。 4. 关闭文件:在文件操作完成后,应该使用 `close()` 函数关闭文件,例如: ```cpp file.close(); ``` 完整的文件读写示例代码如下: ```cpp #include <iostream> #include <fstream> int main() { std::fstream file; file.open("example.txt", std::ios::out); if (file.is_open()) { file << "Hello World!" << std::endl; file.close(); } else { std::cout << "Error opening file!" << std::endl; } file.open("example.txt", std::ios::in); if (file.is_open()) { std::string data; file >> data; std::cout << "Data read from file: " << data << std::endl; file.close(); } else { std::cout << "Error opening file!" << std::endl; } return 0; } ``` 在上述代码中,我们首先打开一个名为 `example.txt` 的文件,并以写入模式向文件中写入数据。之后,我们关闭文件并打开同一个文件,并以读取模式从文件中读取数据。最后,我们将读取的数据输出到控制台并关闭文件。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值