以下定义一个数据结构
c
struct SData {
std::string url;
int number;
std::string memo;
};
写入文件
c
void StorageDataToFile(const std::string& filename, const SData& data) {
std::ofstream outFile(filename);
if (outFile.is_open()) {
// 使用std::stringstream格式化数据
std::stringstream ss;
ss << data.url << "," << data.member << "," << data.memo << "\n";
// 将格式化后的字符串写入文件
outFile << ss.str();
outFile.close();
AfxMessageBox(L"ok storage") ;
}
else {
AfxMessageBox(L"error");
}
}
读取
c
UserData ReadDataFromFile(const std::string& filename) {
SData data;
std::ifstream inFile(filename);
if (inFile.is_open()) {
std::string line;
getline(inFile, line);
std::istringstream iss(line);
if (iss >> data.url>> data.number >> data.memo) {
inFile.close();
return userData;
}
else {
AfxMessageBox(L"error");
}
}
else {
AfxMessageBox(L"error");
}
// 如果读取失败,返回默认构造的UserData
return UserData();
}