CPP文件读写

CPP文件读写

方法一

#include<iostream>
#include <fstream>

using namespace std;

int main()
{
    ifstream s("E://in.txt");
    ofstream o("E://out.txt");

    if (!s.is_open() || !o.is_open())
    {
        cout << "Error Open" << endl;
    }
    else
    {
        string line;
        while (getline(s, line))
        {
            o << line << endl;
        }
        cout << "OK" << endl;
    }
    return 0;
}

方法二

#include<iostream>

using namespace std;

int main()
{
    freopen("E://in.txt", "r", stdin);
    freopen("E://out.txt", "w", stdout);
    string line;
    while (getline(cin,line))
    {
        cout << line << endl;
    }
    return 0;
}
C++提供了一组标准库函数,可以方便地读文件。这些函数都在头文件`<fstream>`中定义。 ### 文件输入 使用`ifstream`类进行文件输入操作。下面是一个例子: ```cpp #include <iostream> #include <fstream> #include <string> using namespace std; int main() { string line; ifstream myfile ("example.txt"); if (myfile.is_open()) { while ( getline (myfile,line) ) { cout << line << '\n'; } myfile.close(); } else cout << "Unable to open file"; return 0; } ``` 这个程序打开一个叫做`example.txt`的文件,并将其内容逐行输出到控制台。 ### 文件输出 使用`ofstream`类进行文件输出操作。下面是一个例子: ```cpp #include <iostream> #include <fstream> using namespace std; int main() { ofstream myfile; myfile.open ("example.txt"); myfile << "Writing this to a file.\n"; myfile.close(); return 0; } ``` 这个程序创建一个叫做`example.txt`的文件,并向其中入一行文本。 ### 二进制文件读写 如果你需要读二进制文件,可以使用`fstream`类。下面是一个例子: ```cpp #include <iostream> #include <fstream> using namespace std; int main() { char data[100]; // 入二进制文件 ofstream outfile; outfile.open("example.bin", ios::binary); outfile.write(data, sizeof(data)); outfile.close(); // 读取二进制文件 ifstream infile; infile.open("example.bin", ios::binary); infile.read(data, sizeof(data)); infile.close(); return 0; } ``` 这个程序向一个二进制文件入一些数据,然后再从文件中读取这些数据。注意,我们在打开文件时使用了`ios::binary`标志,以指示我们要进行二进制文件的读操作。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

zhj12399

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值