c++ - 如何从某些文件中读取并将它们的内容以不同的形式写入具有相同名称的文件中
问题描述
我有一些名称为 f_1to2.txt、f_1to3.txt、f_2to1.txt、f_2to3.txt、...、f_99to100.txt 的文件。我想对这些文件的内容做一些事情,然后将这些更改后的同名文件写入另一个文件夹。我该怎么做?多谢。
解决方案
好的,让我们分析您的需求。
- 您有一个文件名列表。
- 源文件位于源目录中
- 然后你想读取文件并修改它们
- 有一个目标目录,您要在其中存储修改后的文件
- 目标文件文件名将与源文件名相同
所以,让我们逐点解决。
- 你有一个源目录。我们将源目录路径存储在
std::string
.
一个例子可能是:std::string sourceDirectory("c:\\somedir1\\somedir2\\somedir3\\");
然后你有一个或多个文件名。这些可以存储在字符串向量中。例如
std::vector<std::string> fileNameVector{" f_1to2.txt","f_1to3.txt"," f_2to1.txt","f_2to3.txt","f_99to100.txt"};
.下一个活动是打开文件并对它们做一些事情。这你会在一个循环中做。为了打开文本文件进行阅读,我们将使用
std::ifstream
目标目录将存储在 std::string 中
连同文件名和目标目录,我们将为输出文件构建路径并使用
std::ofstream
骨架示例。不是现实生活中的代码
for (const std::string& fileName : fileNameVector){
std::string path = sourceDirectory + fileName; // Build a path
std::ifstream inFile(path); // Open the file
if (inFile) { // Check if file could be opened
std::string line{};
while (std::getline(inFile, line)) { // Read all lines of text file
// Store lines in vector
// Do something
}
inFile.close();
// Build output file path
std::string destinationPath = destinationDirectory + filename;
// Open out file
std::ofstream outFile(destinationPath );
if (outFile) {
// Write all lines to output file
}
}
}
请注意。这只是一个解决方案的建议。没什么具体的。未编译且未测试的骨架代码。
你需要填写你想做的事情。
这应该只是给出一个想法。
您的要求太模糊,无法构建完整的示例。
所以,只是一个想法。
推荐阅读
- java - 无法在 ajax 覆盖弹出窗口中单击或发送键,并使用 selenium 和 java 显示 Element not Intractable 异常
- react-native - [未处理的承诺拒绝:TypeError:_reactNative.NativeModules.RNDatePickerAndroid.dismiss 不是函数
- python - 在postgresql表django中插入数据
- php - 如何保存函数的结果
- javascript - Fabric.js 逐像素操作 Image 对象以改变颜色
- c - C语言中的语法错误
- oracle - Oracle Apex Master Detail Report 和 Detail 报告,带有可供选择的单选按钮选项
- javascript - Mathjax 配置乳胶到中心
- go - 控制 Apache Beam 数据流管道中的并行性
- python - Microsoft Graph API:将 MSAL Python 守护程序应用程序限制为单个用户访问