aboutsummaryrefslogtreecommitdiff
path: root/cpp01/ex07/main.cpp
blob: 64e5ce870a482832acb97610853e00e48fb1a549 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
/* ************************************************************************** */
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   main.cpp                                           :+:      :+:    :+:   */
/*                                                    +:+ +:+         +:+     */
/*   By: cacharle <marvin@42.fr>                    +#+  +:+       +#+        */
/*                                                +#+#+#+#+#+   +#+           */
/*   Created: 2020/02/02 17:08:28 by cacharle          #+#    #+#             */
/*   Updated: 2020/04/13 10:31:55 by charles          ###   ########.fr       */
/*                                                                            */
/* ************************************************************************** */

# include <iostream>
# include <fstream>
# include <string>

int main(int argc, char **argv)
{
	if (argc != 4)
	{
		std::cerr << "Usage: " << argv[0] << " filename s1 s2" << std::endl;
		return 1;
	}
	std::string filename(argv[1]);
	std::string s1(argv[2]);
	std::string s2(argv[3]);
    if (s1 == "" || s2 == "")
    {
		std::cerr << "Error: s1 and s2 should not be empty" << std::endl;
		return 1;
    }

	std::ifstream file(filename);
	std::ofstream outfile(filename + ".replace");
	if (!file)
	{
		std::cerr << "Could not open " << filename;
		outfile.close();
		return 1;
	}
	if (!outfile)
	{
		std::cerr << "Could not create " << filename << ".replace";
		file.close();
		return 1;
	}

	std::string line;
	while (std::getline(file, line))
	{
		while (true)
		{
			size_t i = line.find(s1);
			if (i == std::string::npos)
				break;
			line.replace(i, s1.length(), s2);
		}
		outfile << line << std::endl;
	}
	file.close();
	outfile.close();
    return 0;
}