首页 > 解决方案 > 如何从某些文件中读取并将它们的内容以不同的形式写入具有相同名称的文件中

问题描述

我有一些名称为 f_1to2.txt、f_1to3.txt、f_2to1.txt、f_2to3.txt、...、f_99to100.txt 的文件。我想对这些文件的内容做一些事情,然后将这些更改后的同名文件写入另一个文件夹。我该怎么做?多谢。

标签: c++

解决方案


好的,让我们分析您的需求。

  • 您有一个文件名列表。
  • 源文件位于源目录中
  • 然后你想读取文件并修改它们
  • 有一个目标目录,您要在其中存储修改后的文件
  • 目标文件文件名将与源文件名相同

所以,让我们逐点解决。

  1. 你有一个源目录。我们将源目录路径存储在std::string.

一个例子可能是:std::string sourceDirectory("c:\\somedir1\\somedir2\\somedir3\\");

  1. 然后你有一个或多个文件名。这些可以存储在字符串向量中。例如std::vector<std::string> fileNameVector{" f_1to2.txt","f_1to3.txt"," f_2to1.txt","f_2to3.txt","f_99to100.txt"};.

  2. 下一个活动是打开文件并对它们做一些事情。这你会在一个循环中做。为了打开文本文件进行阅读,我们将使用std::ifstream

  3. 目标目录将存储在 std::string 中

  4. 连同文件名和目标目录,我们将为输出文件构建路径并使用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
        }
    }
}

请注意。这只是一个解决方案的建议。没什么具体的。未编译且未测试的骨架代码。

你需要填写你想做的事情。

这应该只是给出一个想法。

您的要求太模糊,无法构建完整的示例。

所以,只是一个想法。


推荐阅读