c++写数据结构进入文件
以下定义一个数据结构
struct SData {
std::string url;
int number;
std::string memo;
};
写入文件
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");
}
}
读取
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();
}
原文地址:https://blog.csdn.net/qianbo042311/article/details/140464592
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!