patterncppMinor
Append a string to each line in a file
Viewed 0 times
fileeachlineappendstring
Problem
I wrote (several months ago) a program that will take an input file, with a provided
std::string, and append that to each individual line in the file. Looking at the code again, I am wondering about the performance of this program, possibly if the file is very large or any of the lines/input string is long.#include
#include
#include
// argv[1] is input file name
// argv[2] is output file name
// argv[3] is string to add
int main(int argc, const char * argv[])
{
if (argc != 4) {
std::cout vec, result_vec;
while (std::getline(in_file, str)) {
vec.push_back(str);
}
std::for_each(vec.begin(), vec.end(), [&](std::string str) {
result_vec.push_back(str + argv[3]);
});
std::ofstream out_file(argv[2]);
std::copy(result_vec.begin(), result_vec.end(), std::ostream_iterator(out_file, "\n"));
}Solution
There is no need to store all lines from the input file in memory.
For each line read from the input you can append the string and write the
result to the output file. This would save memory for large input files.
You should also check if opening the input and output file was
successful, otherwise your program will silently do nothing if the
files could not be opened/created.
For each line read from the input you can append the string and write the
result to the output file. This would save memory for large input files.
You should also check if opening the input and output file was
successful, otherwise your program will silently do nothing if the
files could not be opened/created.
std::ifstream in_file(argv[1]);
if (!in_file) {
std::cerr << "Could not open input file\n";
return EXIT_FAILURE;
}
std::ofstream out_file(argv[2]);
if (!out_file) {
std::cerr << "Could not create output file\n";
return EXIT_FAILURE;
}
const char * add_string = argv[3];
std::string str;
while (std::getline(in_file, str)) {
out_file << str << add_string << "\n";
}Code Snippets
std::ifstream in_file(argv[1]);
if (!in_file) {
std::cerr << "Could not open input file\n";
return EXIT_FAILURE;
}
std::ofstream out_file(argv[2]);
if (!out_file) {
std::cerr << "Could not create output file\n";
return EXIT_FAILURE;
}
const char * add_string = argv[3];
std::string str;
while (std::getline(in_file, str)) {
out_file << str << add_string << "\n";
}Context
StackExchange Code Review Q#70827, answer score: 6
Revisions (0)
No revisions yet.