收藏文章 楼主

c++ 文件写入

版块:C/C++语言开发   类型:普通   作者:小绿叶技术博客   查看:1754   回复:0   获赞:5   时间:2022-12-29 16:59:11



#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;
}



提供企业建站服务,免费网防系统,提交信息登录 http://yundun.ddoss.cn 邮箱: proposal@ddoss.cn 
回复列表
默认   热门   正序   倒序

回复:c++ 文件写入

头像

用户名:

粉丝数:

签名:

资料 关注 好友 消息