c++ - txt文件的重命名和删除功能不起作用c ++
问题描述
我知道这个问题很多,但我花了几个小时来解决这个问题。我正在尝试通过替换名称来编辑 txt 文件。我将数据复制到 temp.txt 文件中,当我输入输入时,临时文件完成工作并更改单词。但是删除和重命名的功能不起作用。我的代码如下:
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");
}
解决方案
你有两个主要问题。
- 您打开输出文件两次。
- 在执行文件操作之前必须关闭所有文件
尤其是第二个话题引起了麻烦。
这是一个可行的解决方案:
#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;
}
推荐阅读
- r - 为动态条形图的每个条形分配标准颜色
- android - 当我单击列表中的第一个项目时,它会删除所有项目
- c++ - 需要帮助让 tictactoe 游戏中的 minimax 函数正常工作,以使玩家无法获胜
- performance - 当基于用户的协作过滤 (CF) 比基于项目的协作过滤性能更好时,我们可以从数据中推断出什么?
- html - HTML“必需”错误触发方式为时已晚
- python - 如何在python列表中获取具有不同值的元素的随机位置?
- c# - GetAttributeValue 返回为 null
- react-native - 如何在 React Native 中显示延迟的组件?
- python - 使用python将光栅图像转换为多边形
- java - 使用 aws kinesis 时出现“kpl-daemon-0000”java.lang.NoSuchMethodError 异常