forked from DanilBkrestkrest/siaod2-2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfile_operations.cpp
97 lines (83 loc) · 3.14 KB
/
file_operations.cpp
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
#include "file_operations.h"
#include <iostream>
#include <fstream>
#include <sstream>
#include <algorithm>
void createFile(const std::string& fileName) {
std::ofstream file(fileName);
if (file.is_open()) {
file << "Привет, это содержимое файла." << std::endl;
file << "-5 10 -8 7 -3" << std::endl; // Пример содержимого файла с отрицательными числами
std::cout << "Файл " << fileName << " успешно создан." << std::endl;
file.close();
}
else {
std::cerr << "Ошибка при создании файла." << std::endl;
}
}
void printFile(const std::string& fileName) {
std::ifstream file(fileName);
if (file.is_open()) {
std::string line;
std::cout << "Содержимое файла " << fileName << ":" << std::endl;
while (std::getline(file, line)) {
std::cout << line << std::endl;
}
file.close();
}
else {
std::cerr << "Ошибка при открытии файла для чтения." << std::endl;
}
}
void appendToFile(const std::string& fileName, const std::string& content) {
std::ofstream file(fileName, std::ios::app);
if (file.is_open()) {
file << content << std::endl;
std::cout << "Данные успешно добавлены в конец файла " << fileName << "." << std::endl;
file.close();
}
else {
std::cerr << "Ошибка при открытии файла для добавления данных." << std::endl;
}
}
std::vector<int> readNumbersFromFile(const std::string& fileName) {
std::vector<int> numbers;
std::ifstream file(fileName);
if (file.is_open()) {
std::string line;
while (std::getline(file, line)) {
std::istringstream iss(line);
int value;
while (iss >> value) {
numbers.push_back(value);
}
}
file.close();
}
else {
std::cerr << "Ошибка при открытии файла для чтения чисел." << std::endl;
}
return numbers;
}
void replaceNegativeWithSquareOfMin(const std::string& fileName) {
std::vector<int> numbers = readNumbersFromFile(fileName);
if (numbers.empty()) {
std::cerr << "Файл не содержит чисел." << std::endl;
return;
}
int minNumber = *std::min_element(numbers.begin(), numbers.end());
std::ofstream file(fileName);
if (file.is_open()) {
for (int& number : numbers) {
if (number < 0) {
number = minNumber * minNumber;
}
file << number << " ";
}
std::cout << "Отрицательные числа успешно заменены в файле " << fileName << "." << std::endl;
file.close();
}
else {
std::cerr << "Ошибка при открытии файла для замены отрицательных чисел." << std::endl;
}
}