参考:
全网最详细C/C++文件读写总结
https://blog.csdn.net/m0_48643365/article/details/123512860
C/C++文件读写(最全方法,多种实现)
https://blog.csdn.net/weixin_50964512/article/details/123240393
C+±string常用函数整理(建议收藏)
https://blog.csdn.net/zhaitianbao/article/details/118993685
位置从0开始
// CPlusReadWriteFile.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <string>
#include <fstream>
#include <vector>
#include <memory>
#include <iostream>
// 写文件
void writeTxt() {
const unsigned int RowCount = 2;
std::string paraInit[RowCount][2] = { { "QTree","Test" },{ "Rob","Sleep" } };
std::ofstream of;
of.open("Test.txt", std::ios::out | std::ios::trunc);
unsigned int i = 0;
for (int i = 0; i < RowCount; i++)
{
char paraTemp[128] = { 0 };
// 添加空行
//sprintf_s(paraTemp, "[Name]%-32s[Doing]%-32s\n", paraInit[i][0].c_str(), paraInit[i][1].c_str());
// 未添加空行
sprintf_s(paraTemp, "[Name]%-s[Doing]%-s\n", paraInit[i][0].c_str(), paraInit[i][1].c_str());
of.write(paraTemp, strlen(paraTemp));
}
of.close();
}
// 去掉空格
void Trim(std::string &str)
{
if (str.empty())
{
return;
}
str.erase(0, str.find_first_not_of(" "));
str.erase(str.find_last_not_of(" ") + 1);
return;
}
struct MyList
{
std::string name;
std::string doing;
public:
MyList(std::string Name, std::string Doing) :name(Name), doing(Doing) {}
};
std::vector<std::shared_ptr<MyList>> m_List;
// 读文件
void ReadTxt() {
std::ifstream fin;
std::string str = "";
fin.open("Test.txt", std::ios::in);
// 如果打开文件失败创建文件
if (!fin.is_open())
{
writeTxt();
fin.open("Test.txt", std::ios::in);
}
// 每行读取
while (getline(fin, str))
{
// 找到该字符串位置
auto posName = str.find("[Name]");
auto posDoing = str.find("[Doing]");
//auto Name = str.substr(posVendor + sizeof("[Name]") - 1, posModel - posVendor - sizeof("[Name]"));
/*
1.s=ss.substr(1,3); // 提取函数,提取ss字符串从1位置起的3个字符给s字符串
2.s=ss.substr(); // 提取函数,提取ss字符串的所有内容给s字符串
3.s=ss.substr(3); // 提取函数,提取ss字符串从3位置起的所有内容给s字符串
*/
auto Name = str.substr(posName + sizeof("[Name]") - 1, posDoing - posName - sizeof("[Name]")+1);
Trim(Name);
auto Doing = str.substr(posDoing + sizeof("[Doing]") - 1);
Trim(Doing);
std::shared_ptr<MyList> MyListNode = std::make_shared<MyList>(Name, Doing);
m_List.push_back(MyListNode);
}
}
int main()
{
ReadTxt();
std::cout <<"Name:"<< m_List.at(0)->name <<" "<< "Doing:"<<m_List.at(0)->doing
<<std::endl<<"Name:"<< m_List.at(1)->name << " " <<"Doing:"<<m_List.at(1)->doing<<std::endl;
system("pause");
return 0;
}