I am looking for a way to search for a specific character in a text file and add a new-line after every ;
It's a pretty big document (2,7MB) if that matters.
I am looking for a way to search for a specific character in a text file and add a new-line after every ;
It's a pretty big document (2,7MB) if that matters.
As SomeProgrammerdude points out in the comments, inserting into an existing file isn't really feasible and one of your options is to read it all into a single std::string
and write back into the same text file.
Here is an example implementation. We read a charter at a time and check if it is a semicolon, and add a newline after every semicolon. Notice the reserve
part, although advised, it is not mandatory:
#include <string>
#include <fstream>
#include <stdexcept>
int main()
{
std::fstream f("test.txt", std::ios::in);
if (!f.is_open()) {
throw std::runtime_error("Failed to open file");
}
std::string contents;
contents.reserve(10000); // reserve some space for better efficiency
char ch;
while (f.get(ch)) {
contents.push_back(ch);
if (ch == ';')
contents.push_back('\n');
}
f.close();
f.open("test.txt", std::ios::out);
if (!f.is_open()) {
throw std::runtime_error("Failed to open file");
}
f << contents;
f.close();
return 0;
}
Input:
line line line line; line line line line; line line line; line line
Output:
line line line line;
line line line line;
line line line;
line line
Note the leading spaces before lines. This is because we appended '\n'
after every ';'
, did not replace the spaces.
You can't insert new characters into the middle of an existing file, only append to the end. You will have to create a new file, copying characters from the old file to the new file, inserting new characters as needed. For example:
#include <string>
#include <fstream>
int main()
{
std::ifstream inFile("input.txt");
if (!inFile.is_open())
{
std::cerr << "Failed to open input file";
return 1;
}
std::ofstream outFile("output.txt");
if (!outFile.is_open())
{
std::cerr << "Failed to create output file";
return 1;
}
std::string line;
while (std::getline(inFile, line, ';'))
{
outFile << line;
if (!inFile.eof())
outFile << ";\n";
}
return 0;
}