#include <fstream>
#include <iostream>
using namespace std;
//--- 文件和流 ---
// ofstream 输出文件流,用于创建并写入文件; ifstream 输入文件流,用于读取文件; fstream 文件流,同时有前面两种功能
int main ()
{
char data[100];
// 以写模式打开文件, 定义一个文件打开函数 SetFile
ofstream SetFile;
SetFile.open("1.txt");
cout << "Enter your name: ";
cin.getline(data, 100);
// 向文件写入用户输入的数据, 前面定义为 打开 1.txt
SetFile << data << endl;
cout << "Enter your age: ";
cin >> data;
// 输入到变量
cin.ignore();
// cin.ignore常用功能:清除以回车结束的输入缓冲区的内容,消除上一次输入对下一次输入的影响
// 再次向文件写入用户输入的数据
SetFile << data << endl;
// 关闭打开的文件
SetFile.close();
// 以读模式打开文件
ifstream infile;
infile.open("1.txt",ios::in);
// ios::app 追加模式,写入到文件末尾 ; ios::ate 打开文件定位到末尾 ;ios::in 打开文件用于读取; ios::out 打开文件用于写入 ; ios::trunc 打开文件,存在就被截断,长度为 0
cout << "Reading from the file" << endl;
infile >> data;
// 在屏幕上写入数据
cout << data << endl;
// 再次从文件读取数据,并显示它
infile >> data;
cout << data << endl;
// 关闭打开的文件
infile.close();
return 0;
}
Powered by ddoss.cn 12.0
©2015 - 2025 ddoss
渝公网安备50011302222260号
渝ICP备2024035333号
【实验平台安全承诺书】
小绿叶技术社区,优化网络中,点击查看配置信息
主机监控系统: 安全防火墙已开启检查cc攻击-下载文件完成后等待10s 恢复访问,检查连接数低于峰值恢复访问
您的IP:216.73.216.110,2025-12-01 15:24:02,Processed in 0.01485 second(s).