重命名和删除txt文件的功能不起作用C ++

奥努尔·奥祖佩克(Onur Ozupek)

我知道这个问题很多,但是我要花几个小时来解决这个问题。我正在尝试通过替换名称来编辑txt文件。我将数据复制到temp.txt文件中,当我输入输入内容时,temp文件完成了工作并更改了单词。但是删除和重命名功能不起作用。我的代码如下:

string search_string;

    string replace_string;

   ofstream file;

    file.open("temp.txt"); //opening file

    cout<<"Enter the word you want to change: ";

    cin>>search_string;

    cout<<"Enter the new word: ";

    cin>>replace_string;

    string inbuf;

    fstream input_file("musics.txt", ios::in);

    ofstream output_file("temp.txt");

  while (!input_file.eof())
  {
      getline(input_file, inbuf);

      int spot = inbuf.find(search_string);

 if(spot >= 0)
      {
    'this is the replacing part' 
      }  
     output_file << inbuf << endl;

    remove("musics.txt");

    file.close();

    rename("temp.txt", "musics.txt");
}
阿明·蒙蒂尼(Armin Montigny)

您有2个主要问题。

  • 您打开输出文件两次。
  • 必须先关闭所有文件,然后才能执行文件操作

尤其是第二个话题正在引起麻烦。

这是一个可行的解决方案:

#include <iostream>
#include <cstdio>
#include <fstream>
#include <regex>

// The filenames
const std::string musicFileName{ "music.txt" };
const std::string tempFileName{ "temp.txt" };


int main() {

    // Open a new scope, so that the file streams 
    // will be closed automatically by the destructor
    {
        // Open the source file
        std::ifstream sourceFile(musicFileName);

        // Check, if it could be opened
        if (sourceFile) {

            // Source file is open, now open the temp file
            std::ofstream tempFile(tempFileName);

            // Check, if the tempfile could be opened
            if (tempFile) {

                // Both files are open, get the search and replace strings
                std::string searchString;
                std::string replaceString;

                std::cout << "Enter the word you want to change: ";
                std::cin >> searchString;

                std::cout << "Enter the new word: ";
                std::cin >> replaceString;

                // Now read all lines from source file
                std::string textLine{};
                while (std::getline(sourceFile, textLine)) {

                    // Replace the text and write it to the destination file
                    tempFile << std::regex_replace(textLine, std::regex(searchString), replaceString) << "\n";
                }
            }
            else {
                std::cerr << "Could not open '" << tempFileName << "'\n";
            }
        }  //  <-- This will close the temp file
        else {
            std::cerr << "Could not open '" << musicFileName << "'\n";
        }
    }  //  <-- This will close the source file

    // Remove and rename
    std::remove(musicFileName.c_str());
    std::rename(tempFileName.c_str(), musicFileName.c_str());

    return 0;
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章