I am currently learning C++. I coded a tiny program for school and I wonder if there could be issues (like bugs or security issues) with it.
Any ways to make it have weird behaviours would be very appreciated, any suggestions to improve my code in terms or performance or readability are also welcomed.
Instructions
Given a file named
filename
, and two stringss1
ands2
, this program should create a new file namedfilename.replace
in which all occurrences ofs1
are replaced bys2
.
- code needs to compile with the
-std=c++98
flag (so no C++11 standard or more) - I only can use the standard library's functions
- no
*printf
,*alloc
orfree
- no C file manipulation functions, only C++
- no
STL
, no containers nor<algorithm>
header - no
std::string::replace
function
#include <iostream>
#include <fstream>
int main( int ac, char **av )
{
if (ac != 4) {
std::cout << "Invalid number of arguments" << std::endl;
return -1;
}
std::string infile_name(av[1]);
std::fstream infile(infile_name, std::ios::in);
if (!infile.is_open()) {
std::cout << "'" << av[1]
<< "': issue while opening the file" << std::endl;
return -1;
}
std::cout << "'" << av[1]
<< "': successfully opened in read mode" << std::endl;
std::string outfile_name(av[1]);
outfile_name += ".replace";
std::fstream outfile(outfile_name, std::ios::out | std::ios::trunc);
if (!outfile.is_open()) {
std::cout << "'" << av[1]
<< "': issue while opening the file" << std::endl;
return -1;
}
std::cout << "'" << outfile_name
<< "': successfully opened and truncated in write mode" << std::endl;
std::string line;
std::string s1(av[2]);
std::string s2(av[3]);
size_t pos;
while (std::getline(infile, line)) {
if (!infile.eof())
line += '\n';
do {
pos = line.find(s1);
if (pos == std::string::npos)
outfile << line;
else {
outfile << line.substr(0, pos);
outfile << s2;
line = line.substr(pos + s1.size());
}
} while (pos != std::string::npos);
}
// not necessary to close the files manually as std::fstream objects are RAII
// objects: https://stackoverflow.com/questions/4802494/do-i-need-to-close-a-stdfstream
// infile.close();
// outfile.close();
}
std::string
, which is sufficient for this. Perhaps the prof will have them coding their own implementations of the data structures shortly. \$\endgroup\$