aboutsummaryrefslogtreecommitdiff
path: root/cpp01/ex07/main.cpp
blob: fbef95fc286474dc14a1aa9e250ce3640ba66ee7 (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
/* ************************************************************************** */
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   main.cpp                                           :+:      :+:    :+:   */
/*                                                    +:+ +:+         +:+     */
/*   By: cacharle <marvin@42.fr>                    +#+  +:+       +#+        */
/*                                                +#+#+#+#+#+   +#+           */
/*   Created: 2020/02/02 17:08:28 by cacharle          #+#    #+#             */
/*   Updated: 2020/02/02 18:00:25 by cacharle         ###   ########.fr       */
/*                                                                            */
/* ************************************************************************** */

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

int main(int argc, char **argv)
{
	if (argc != 4)
	{
		std::cerr << "Usage: " << argv[0] << " filename s1 s2";
		return 1;
	}
	std::string filename(argv[1]);
	std::string find_str(argv[2]);
	std::string replace_str(argv[3]);

	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(find_str);
			if (i == std::string::npos)
				break;
			line.replace(i, find_str.length(), replace_str);
		}
		outfile << line << std::endl;
	}
	file.close();
	outfile.close();
}