您的位置:首页 > 编程语言 > C语言/C++

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

2015-08-13 19:50 691 查看
#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相关信息,进行续播。其实应该在关闭的时候存信息,为了代码简单,所以写在了打开时。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: