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相关信息,进行续播。其实应该在关闭的时候存信息,为了代码简单,所以写在了打开时。
相关文章推荐
- [C++] volatile
- C++中this指针的本质
- 用OC语言完成简易通讯录(实现增删改查)功能.
- stm32编译前为什么要配置keil中C/C++中的define 和include Paths?
- c/c++里的 堆区 栈区 静态区 文字常量区 程序代码区
- C++ 友元(共享数据)
- C++创建于销毁对象
- [转]C/C++中的memset
- C++ 类 互相包含的问题研究
- C和C++格式化输入输出
- 基本排序算法之快速排序
- VS2010 C++ 学习笔记(三) 类和对象 访问限定符 String
- c语言捕捉异常
- 二叉树的C++实现
- VS中的路径宏 vc++中OutDir、ProjectDir、SolutionDir各种路径
- 【c++】字符串中找出最长的连续数字字符串
- c语言为什么要声明
- Minimum Transport Cost
- 黑马程序员———C语言———【函数指针、指针函数、野指针、内存管理、const关键字】
- C++ primer 【笔记】关联容器 set