main.cpp
1 /* ************************************************************************** */ 2 /* */ 3 /* ::: :::::::: */ 4 /* main.cpp :+: :+: :+: */ 5 /* +:+ +:+ +:+ */ 6 /* By: gychoi <gychoi@student.42seoul.kr> +#+ +:+ +#+ */ 7 /* +#+#+#+#+#+ +#+ */ 8 /* Created: 2023/07/27 17:05:36 by gychoi #+# #+# */ 9 /* Updated: 2023/07/28 03:43:36 by gychoi ### ########.fr */ 10 /* */ 11 /* ************************************************************************** */ 12 13 #include <iostream> 14 #include <fstream> 15 #include <sstream> 16 #include <string> 17 18 std::string editString(const std::string& str, const std::string& pattern, const std::string& replacement) 19 { 20 std::string output; 21 std::size_t pos = 0; 22 std::size_t strLength = str.length(); 23 std::size_t patternLength = pattern.length(); 24 25 if (!patternLength || !strLength || static_cast<int>(strLength - patternLength) < 0) 26 return (str); 27 while (pos <= strLength - patternLength) 28 { 29 if (str.substr(pos, patternLength) == pattern) 30 { 31 output += replacement; 32 pos += patternLength; 33 } 34 else 35 output += str[pos++]; 36 } 37 output += str.substr(pos); 38 return (output); 39 } 40 41 int main(int argc, char* argv[]) 42 { 43 if (argc != 4) 44 { 45 std::cout << "Usage: " << argv[0] << " <filename> <s1> <s2>" << std::endl; 46 return (1); 47 } 48 const std::string infile = argv[1]; 49 const std::string s1 = argv[2]; 50 const std::string s2 = argv[3]; 51 std::ostringstream buffer; 52 std::ifstream ifs(infile.c_str()); 53 if (ifs.fail()) 54 { 55 std::cout << "Error: Cannot open input file: " << infile << std::endl; 56 return (1); 57 } 58 else 59 { 60 buffer << ifs.rdbuf(); 61 ifs.close(); 62 } 63 std::string output = editString(buffer.str(), s1, s2); 64 const std::string outfile = infile + ".replace"; 65 std::ofstream ofs(outfile.c_str()); 66 if (ofs.fail()) 67 { 68 std::cout << "Error: Cannot create output file: " << outfile << std::endl; 69 return (1); 70 } 71 else 72 ofs << output; 73 return (0); 74 }