Files
CS-LABS/lab_1/12_first_symbols_to_spaces.cpp
2025-10-01 18:24:17 +07:00

73 lines
1.9 KiB
C++

// Task 12 (Ubuntu): replace every char equal to the first char of its line with a space.
// Usage: ./task12 <input_file> → writes "<input_file>.out" and prints replacement count.
#include <iostream>
#include <fstream>
#include <string>
#include <sys/stat.h>
// True if file exists (POSIX stat)
static bool file_exists(const std::string &path) {
struct stat st{};
return ::stat(path.c_str(), &st) == 0;
}
// "<name>.out" by replacing last extension or appending if none
static std::string make_out_name(const std::string &in) {
std::size_t pos = in.find_last_of('.');
if (pos == std::string::npos) return in + ".out";
return in.substr(0, pos) + ".out";
}
int main(int argc, char *argv[]) {
if (argc != 2) {
std::cerr << "Usage: " << argv[0] << " <input_file>\n";
return -1;
}
std::string in_path = argv[1];
if (!file_exists(in_path)) {
std::cerr << "Error: input file does not exist.\n";
return -1;
}
std::ifstream in(in_path);
if (!in) {
std::cerr << "Error: cannot open input file.\n";
return -1;
}
std::string out_path = make_out_name(in_path);
std::ofstream out(out_path);
if (!out) {
std::cerr << "Error: cannot create output file.\n";
return -1;
}
long long replacements = 0;
std::string line;
while (std::getline(in, line)) {
if (!line.empty()) {
char first = line.front();
for (char &c: line) {
if (c == first) {
if (c != ' ') {
c = ' ';
++replacements;
} // count only real changes
}
}
}
out << line;
if (!in.eof()) out << '\n';
if (!out) {
std::cerr << "Error: write error.\n";
return -1;
}
}
std::cout << replacements << std::endl;
return static_cast<int>(replacements);
}