C++ 创建、读写文件操作 fstream

#include <iostream> 
#include <fstream> 
#include <string>
#include <sstream>// stringstream

using namespace std; 

int main() 
{ 
	string filePath1 = "D:/Test/mm11111.mp3"; 
	//string filePath1 = "filePath.mp3"; 
	string filePath2 ; 
	int m_lastStopTime = 11;// 上次movie播放的相关信息,用于续播
	int m_lastvideoIndex = 34;
	int m_lastaudioIndex = 20;
	int m_lastsubStreamIndex =44; 


	cout<<"The length of filePath1 = "<<filePath1.size()<<endl;
	int j;
	for(j=filePath1.size()-1;j>=0 && filePath1[j]!='.';j--);//找到filePath1中最后一个‘.’
	cout<<"j = "<<j<<endl;
	for(int i=0;i<j;i++)//将后缀名为mp3的filePath1路径改为后缀名为txt的filePath2路径
	{
		filePath2.push_back(filePath1[i]);
	}
	filePath2.push_back('.');
	filePath2.push_back('t');
	filePath2.push_back('x');
	filePath2.push_back('t');
	cout<<"The path of file2 is ["<<filePath2<<']'<<endl;

	ifstream infile(filePath2); // open filePath2
	if(!infile)//不存在则创建filePath2,并将movie相关信息存入该文件,便于下次续播
	{
		cout<<filePath2<<" does not exist!!"<<endl;

		ofstream outfile(filePath2,ios::out);//creat filePath file
		if (!outfile)
		{
			cerr<<"open error"<<endl;
			exit(1);
		}
		outfile<<m_lastStopTime<<endl;
		outfile<<m_lastvideoIndex<<endl;
		outfile<<m_lastaudioIndex<<endl;
		outfile<<m_lastsubStreamIndex<<endl;

		/*outfile<<1<<endl;
		outfile<<2<<endl;
		outfile<<3<<endl;
		outfile<<4<<endl;*/

		outfile.close();
	}
	else//如果存在则读出该movie的相关信息,进行续播
	{
		cout<<"inflie open success"<<endl;

		string sLine;
		int index=0;
		while(getline(infile,sLine))// 一行一行读取
		{
			stringstream strTmp;
			strTmp<<sLine;
			cout<<"index = "<<index<<endl;
			cout<<sLine<<endl;
			if(index==0)
				strTmp>>m_lastStopTime;//借用stringstream将读取的一行字符串转化成int型
			else if(index==1)
				strTmp>>m_lastvideoIndex;
			else if(index==2)
				strTmp>>m_lastaudioIndex;
			else if(index==3)
				strTmp>>m_lastsubStreamIndex;
			index++;
		}	
		infile.close();

		cout<<"m_lastStopTime = "<<m_lastStopTime<<endl;
		cout<<"m_lastvideoIndex ="<<m_lastvideoIndex<<endl;
		cout<<"m_lastaudioIndex = "<<m_lastaudioIndex<<endl;
		cout<<"m_lastsubStreamIndex ="<<m_lastsubStreamIndex<<endl;
	}
	system("pause");
	return 0; 
}


每次播放movie前都会判断上次有没有打开过,如果没有打开则创建同名txt文档,将movie的相关信息存进去,如果同名txt文档存在,则说明已经打开过,读取movie相关信息,进行续播。其实应该在关闭的时候存信息,为了代码简单,所以写在了打开时。

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值