-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexercisefile.cpp
More file actions
57 lines (40 loc) · 1.46 KB
/
Copy pathexercisefile.cpp
File metadata and controls
57 lines (40 loc) · 1.46 KB
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
#include <iostream>
#include <vector>
#include <fstream>
using namespace std;
int main() {
vector<string> vec; // Vettore per memorizzare le righe del file
ifstream file; // Dichiarazione del file in input
string path = "exemp.txt"; // Percorso del file
file.open(path); // Apertura del file
if (file.is_open()) { // Controllo se il file è stato aperto correttamente
string buffer; // Variabile temporanea per leggere le righe
while (getline(file, buffer)) { // Legge una riga alla volta
vec.push_back(buffer); // Aggiunge la riga letta al vettore
}
file.close(); // Chiude il file dopo la lettura
// Stampa le righe lette
for (size_t i = 0; i < vec.size(); i++) {
cout << vec[i] << endl;
}
}
ofstream file1; // Apre il file in scrittura (svuotandolo!)
file1.open(path);
for (int i = vec.size() - 1; i >= 0; i--) {
file1 << vec[i] << endl; // Scrive nel file
}
file1.close();
// Rileggiamo il file modificato per mostrarlo
ifstream file2(path); // Riapertura per rilettura
if (!file2.is_open()) {
string buffer1;
cout << "Errore nella rilettura del file!" << endl;
return 1;
cout << "\nContenuto invertito del file:" << endl;
while (getline(file2, buffer1)) {
cout << buffer1 << endl;
}
file2.close();
}
return 0;
}