C++创建文件时出错(名称基于其他文件名)
我在创建一个文件时遇到问题,该文件的名称从其他文件的名称中稍微修改了一些。
但是,如果新名称不是基于另一个名称 - 程序可以运行 - 但我需要使用第一种方法。
我使用反斜杠 ( b)".srt"从原始文件名中删除以修改副本 - 在此程序中,我无法修改path_file_1和path_file_2,因此我不能错过扩展名并在我完成准备副本后添加它。
这是代码:
#include <iostream>
#include <fstream>
int main()
{
std::cout << "Starrting!" << std::endl;
std::string path_file_1 = "Sub-File1.srt";
std::string path_file_2 = "Sub-File2.srt";
std::string path_file_new = path_file_1 + "bbbb-corr.srt";
//std::string path_file_new = "Sub-File1-corr.srt";
//this works!
std::cout << path_file_1 << std::endl;
std::cout << path_file_new << std::endl;
//Creating a new file
std::fstream file;
file.open(path_file_new, std::ios::out | std::ios::binary);
if (!file)
{
std::cout << "Error in creating file!!!";
return 0;
}
std::cout << "File created successfully." << std::endl;
file.close();
}
这是输出:
Starrting!
Sub-File1.srt
Sub-File1-corr.srt
Error in creating file!!!
回答
添加bbbb到您的字符串会添加 4 个退格字符。它不会char从字符串中删除 4 s。
这会起作用:
std::string path_file_new = path_file_1.substr(0, path_file_1.size()-4) + "-corr.srt";