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

来源:互联网 发布:java如何执行cmd命令 编辑:程序博客网 时间:2024/05/17 02:46
#include <iostream> #include <fstream> #include <string>#include <sstream>// stringstreamusing 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 filePath2if(!infile)//不存在则创建filePath2,并将movie相关信息存入该文件,便于下次续播{cout<<filePath2<<" does not exist!!"<<endl;ofstream outfile(filePath2,ios::out);//creat filePath fileif (!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 0