C++读取写入.txt文件(ifstream/ofstream)—读取指定行,修改指定行,复制文件,清除文件,统计文件行数
来源:互联网 发布:网络软文推广公司 编辑:程序博客网 时间:2024/04/30 04:28
C++对txt文件的操作是基于fstream/ifstream/ofstream类的,使用时需添加头文件包含:
#include<fstream>针对txt文件的操作大体包括基本的读写,读取指定行,修改指定行,复制文件,清除文件,统计文件行数等几种,分别实现如下;
以下重点在于实现几个操作,关于这一块的基础知识参考:C++文件读写详解(ofstream,ifstream,fstream)
1、统计txt文件行数;
/***统计txt文件行数*/int CountLines(string filename){ifstream ReadFile;int n = 0;string tmp;ReadFile.open(filename, ios::in);//ios::in 表示以只读的方式读取文件 if (ReadFile.fail())//文件打开失败:返回0 {return 0;}else//文件存在 {while (getline(ReadFile, tmp, '\n')){n++;}ReadFile.close();return n;}}2、复制txt文件;
/***复制txt文件*/void copyTxt(string srcFilename, string dstFilename){ifstream infile;ofstream outfile;string temp;infile.open(srcFilename, ios::in);outfile.open(dstFilename, ios::trunc | ios::out);if (infile.good()){while (!infile.eof()){getline(infile, temp, '\n');outfile << temp << '\n';}}infile.close();outfile.close();}3、清除txt文件;
/***清除txt文件*/void clearTxt(string filename){ofstream text;text.open(filename, ios::out | ios::trunc);//如果重新设置需要text.close();}4、修改指定行数据
/***修改指定行数据*/void ResetLine(string file,int line){int total = CountLines(file);if (line > total || line < 1){MessageBox(_T("修改超出配置文件行数范围"));return;}string bup = _T(".\\tmp.txt");//备份文件copyTxt(file,bup);ifstream rfile;ofstream wfile;rfile.open(bup,ios::in);wfile.open(file,ios::out|ios::trunc);string str;int i = 1;while (!rfile.eof()){if (i == line){CString strMFC;strMFC.Format(_T("%f %f %f\n"), m_pAssistCam, m_tAssistCam, m_zAssistCam);wfile << strMFC.GetBuffer(0);//写入修改内容}else{//rfile.getline()getline(rfile, str, '\n');wfile << str << '\n';}i++;}rfile.close();wfile.close();}5、读取指定行数据
/* **读取txt指定行数据存入string */string readTxt(string filename, int line){//line行数限制 1 - linesifstream text;text.open(filename, ios::in);vector<string> strVec;while (!text.eof()) //行0 - 行lines对应strvect[0] - strvect[lines]{string inbuf;getline(text, inbuf, '\n');strVec.push_back(inbuf);}return strVec[line - 1];}
阅读全文
0 0
- C++读取写入.txt文件(ifstream/ofstream)—读取指定行,修改指定行,复制文件,清除文件,统计文件行数
- C++读取写入.txt文件(ifstream/ofstream)—读取指定行,修改指定行,复制文件,清除文件,统计文件行数
- 指定行数读取log文件
- Python 实例一 统计指定文件的行数或读取指定文件指定行数的内容
- 读取文件指定行
- python读取指定文件指定行数内容
- python读取指定文件指定行数内容
- vb 读取文件指定行
- 读取文件指定行linecache
- Java按指定行数读取文件
- Java按指定行数读取文件
- Java按指定行数读取文件
- Java按指定行数读取文件 .
- Java按指定行数读取文件
- 读取指定行数文件内容并显示
- 读取和写入.INI文件的指定行
- Java中从指定txt读取文件
- IDL读取txt文件行数
- JQuery.getJSON 从aspx页面返回JSON数据
- Java开发中的23种设计模式详解
- 欢迎使用CSDN-markdown编辑器
- HashMap和Hashtable的区别
- Android 开源App:发呆便签/SuperNote
- C++读取写入.txt文件(ifstream/ofstream)—读取指定行,修改指定行,复制文件,清除文件,统计文件行数
- Tencent2017秋招笔试题--求编码的index
- c++32/64位编译器简单获取cpuid低32位代码
- cron定时器_爬虫_获取每日星座运势
- Apache Tephra -使用
- 类的成员变量通过Field.set方法提示java.lang.NullPointerException
- IP转数字,数字转IP
- Meteor Shower POJ
- RobotFrameWork之For循环应用