Compare commits
2 Commits
f063902349
...
84b0db8c9c
Author | SHA1 | Date | |
---|---|---|---|
|
84b0db8c9c | ||
|
ed9b31a1c9 |
0
ex03/obj/.gitkeep
Normal file
0
ex03/obj/.gitkeep
Normal file
66
ex04/src/main.cpp
Normal file
66
ex04/src/main.cpp
Normal file
@ -0,0 +1,66 @@
|
||||
#include <cstddef>
|
||||
#include <ostream>
|
||||
#include <string>
|
||||
#include <iostream>
|
||||
#include <fstream>
|
||||
#include <cstring>
|
||||
|
||||
static int get_text(const char *path, std::string &text)
|
||||
{
|
||||
std::ifstream file(path);
|
||||
std::string line;
|
||||
|
||||
if (!file.is_open())
|
||||
{
|
||||
std::cerr << "sed: file error" << std::endl;
|
||||
return (1);
|
||||
}
|
||||
while (std::getline(file, line))
|
||||
text += line + "\n";
|
||||
if (text.size() != 0)
|
||||
text.erase(text.size() - 1);
|
||||
file.close();
|
||||
return (0);
|
||||
}
|
||||
|
||||
static std::string replace_text(const char *text, const char *text_to_replace, const std::string &replacement_text)
|
||||
{
|
||||
size_t i;
|
||||
size_t len;
|
||||
std::string out;
|
||||
|
||||
len = std::strlen(text_to_replace);
|
||||
i = 0;
|
||||
while (text[i] != '\0')
|
||||
{
|
||||
if (len != 0 && std::strncmp(text + i, text_to_replace, len) == 0)
|
||||
{
|
||||
out += replacement_text;
|
||||
i += len;
|
||||
}
|
||||
else
|
||||
{
|
||||
out += text[i];
|
||||
i++;
|
||||
}
|
||||
}
|
||||
return (out);
|
||||
}
|
||||
|
||||
int main(int ac, char **av)
|
||||
{
|
||||
std::string text;
|
||||
std::string replaced;
|
||||
|
||||
if (!(ac >= 4))
|
||||
{
|
||||
std::cerr << "Sed: missing argument" << std::endl
|
||||
<< "syntax: ./sed file text_to_replace replacement_text" << std::endl;
|
||||
return (1);
|
||||
}
|
||||
if (get_text(av[1], text))
|
||||
return (2);
|
||||
std::cout << text << std::endl;
|
||||
replaced = replace_text(text.c_str(), av[2], av[3]);
|
||||
std::cout << replaced << std::endl;
|
||||
}
|
Loading…
Reference in New Issue
Block a user