Reputation: 67
I have a problem with creating a file, whose name is a little bit modified from some other file's name.
But if the new name is not based on another name - the program works - but I need to use that first method.
I used backslash (\b
) to remove ".srt"
from the original file name to modify the copy - in this program, I cannot modify path_file_1
and path_file_2
, so I cannot just miss the extension and add it later when I finished preparing the copy.
Here's the code:
#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 + "\b\b\b\b-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();
}
Here's the output:
Starrting!
Sub-File1.srt
Sub-File1-corr.srt
Error in creating file!!!
Upvotes: 3
Views: 299
Reputation: 596121
As others have stated, you can't use backslash characters to remove characters, you would need to use string::substr()
instead in this particular situation.
If you are using C++17 or later, you can use the <filesystem>
library to manipulate file paths more easily, eg:
#include <iostream>
#include <fstream>
#include <filesystem>
namespace fs = std::filesystem;
int main()
{
std::cout << "Starrting!" << std::endl;
fs::path path_file_1 = "Sub-File1.srt";
fs::path path_file_new = path_file_1.stem(); // removes the extension...
path_file_new += "-corr.srt";
std::cout << path_file_1 << std::endl;
std::cout << path_file_new << std::endl;
//Creating a new file
std::ofstream file(path_file_new, std::ios::binary);
if (!file.is_open())
{
std::cout << "Error in creating file!!!";
return 0;
}
std::cout << "File created successfully." << std::endl;
file.close();
}
Upvotes: 4
Reputation: 25388
Using backspaces for this won't cut it, unfortunately. Displaying the filename is misleading because they will have the desired effect on the display, but the filename itself will not be correct because it will contain actual backslash characters.
Instead, you want what Ted says in his answer - make a shortened version of the original string and add the desired suffix.
Upvotes: 3
Reputation: 117298
Adding \b\b\b\b
to your string adds 4 backspace characters. It does not remove 4 char
s from the string.
This would work:
std::string path_file_new = path_file_1.substr(0, path_file_1.size()-4) + "-corr.srt";
Upvotes: 7