C++读取写入文件(ifstreamofstream)—读取指定行,修改指定行,复。。。
C++读取写⼊.txt⽂件(ifstreamofstream)—读取指定⾏,修
改指定⾏,复。。。
针对txt⽂件的操作⼤体包括基本的读写,读取指定⾏,修改指定⾏,复制⽂件,清除⽂件,统计⽂件⾏数等⼏种,分别实现如下;工作证明样本
以下重点在于实现⼏个操作,关于这⼀块的基础知识参考:
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;
}
}
武侠 小说/*
**复制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 (d())
{
while (!f())
{
getline(infile, temp, '\n');
outfile << temp << '\n';
}
}
infile.close();
outfile.close();
}
**清除txt⽂件
*/
void clearTxt(string filename)
{
ofstream text;
text.open(filename, ios::out | ios::trunc);//如果重新设置需要
进口奶粉什么牌子好
四姑娘山旅游攻略text.close();
}
/*
**修改指定⾏数据
*/
void ResetLine(string file,int line)
{
int total = CountLines(file);
if (line > total || line < 1)
{
MessageBox(_T("修改超出配置⽂件⾏数范围"));
return;
}
洗面奶品牌排行榜
string bup = _T(".\\");//备份⽂件
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 (!f())
{
if (i == line)
{
CString strMFC;
strMFC.Format(_T("%f %f %f\n"), m_pAssistCam, m_tAssistCam, m_zAssistCam);              wfile << strMFC.GetBuffer(0);//写⼊修改内容
}
else
{
//line()
getline(rfile, str, '\n');
wfile << str << '\n';
}
i++;
}
rfile.close();
wfile.close();
}
**读取txt指定⾏数据存⼊string
*/
string readTxt(string filename, int line)
{
//line⾏数限制 1 - lines
ifstream text;
text.open(filename, ios::in);
vector<string> strVec;
while (!f())  //⾏0 - ⾏lines对应strvect[0] - strvect[lines]
{
string inbuf;
getline(text, inbuf, '\n');
strVec.push_back(inbuf);
}
return strVec[line - 1];
}
转⾃blog.csdn/m0_37901643/article/details/75634657

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。