文件的创建与读取 文件的数据添加

文件的创建与读取   文件的数据添加

一:概要

1:首先要站在程序的角度上。

2:文件的创建 即将程序中的数据 写入到文件当中。

3:文件的读取 即将一个文件中的信息读取到程序当中。

二:步骤

1:创建文件流

2:打开文件流

3:往文件中写入数据

4:关闭文件流

注意:第一步和第二步可以合并为一步 即:ofstream ofile("num.txt",ios::out);

三:上代码

1:文件的创建:

#include<bits/stdc++.h>
using namespace std;


//先创建一个文件 然后往文件里写东西  
int main()
{
	int a[5] = { 1,2,3,4,5};
	//创建文件;
	ofstream ofile;   //ofstream ofile("num.txt",ios::out); 
	//打开文件
	ofile.open("num.txt",ios::out);	
	if( ofile == NULL)
	{
		cout << "open fail" << endl;
		exit(1);
	}
	
	//向文件中写入数据
	
	for( int i = 0; i < 5; i++ )
	{
		ofile << a[i] << ' ';	
	} 
	
	//关闭流文件
	
	ofile.close(); 
} 

2:文件的读取(将一个文件中的数据读入到代码当中)

#include<bits/stdc++.h>
using namespace std;

int main()
{
	int b[5];
	//创建文件 
	ifstream ifile;
	//打开文件
	ifile.open("num.txt", ios::in);//从程序的角度出发  读入一个文件
	
	if( ifile == NULL)
	{
		cout << "fail" << endl;
		exit(1);	
	}
	for( int i = 0; i < 5; i++ )
	{
		ifile >> b[i];	
	}
	
	ifile.close();
	for( int i = 0; i < 5; i++ )
	{
		cout << b[i] << ' ';	
	}	
} 

3:在一个文件中的内容已有的情况下 存入数据

#include<bits/stdc++.h>
using namespace std;

int main()
{
	int a[5] = { 1,2,3,4,5};
	//创建文件;
	ofstream ofile;   //ofstream ofile("num.txt",ios::out); 
	//打开文件
	ofile.open("num.txt",ios::out);	
	if( ofile == NULL)
	{
		cout << "open fail" << endl;
		exit(1);
	}
	
	//向文件中写入数据
	
	for( int i = 0; i < 5; i++ )
	{
		ofile << a[i] << ' ';	
	} 
	
	//关闭流文件
	ofile.close();
	
	int temp = 100;
	ofile.open("num.txt",ios::app);
	
	ofile << ' ' << temp;
	
	ofile.close(); 
}  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

天天向上的菜鸡杰!!

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

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

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

打赏作者

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

抵扣说明:

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

余额充值