78 lines
1.7 KiB
C++
78 lines
1.7 KiB
C++
/*
|
|
Nome: Mario
|
|
Cognome: Montanari
|
|
Classe: 3AIN
|
|
Data: 04/04/2025
|
|
|
|
es03. (contacaratteri)
|
|
Scrivere una funzione che, ricevuto in ingresso il nome di un file,
|
|
restituisca il conteggio dei caratteri presenti al suo interno oppure
|
|
-1 nel caso in cui non sia possibile accedere al file. Utilizzare la
|
|
funzione per mostrare il numero di caratteri dei file in.txt, in2.txt
|
|
e nonesiste.txt (si supponga che quest'ultimo file non sia presente nel
|
|
disco), emettendo un apposito messaggio in presenza di errori di apertura
|
|
dei file.
|
|
*/
|
|
|
|
#include <iostream>
|
|
|
|
using namespace std;
|
|
|
|
int contaChrFile(const char * nomeFile);
|
|
void copiaFile(const char * nomeFileSorgente, const char * nomeFileDestinazione);
|
|
|
|
int main(void) {
|
|
cout << "Caratteri in 'in.txt': " << contaChrFile("in.txt") << endl;
|
|
copiaFile("in.txt", "in2.txt");
|
|
cout << "Caratteri in 'in2.txt': " << contaChrFile("in2.txt") << endl;
|
|
copiaFile("in.txt", "nonesiste.txt");
|
|
cout << "Caratteri in 'nonesiste.txt': " << contaChrFile("nonesiste.txt") << endl;
|
|
|
|
return 0;
|
|
}
|
|
|
|
int contaChrFile(const char * nomeFile) {
|
|
int countChr = 0;
|
|
|
|
FILE * fp = fopen(nomeFile, "rt");
|
|
|
|
if (fp != NULL) {
|
|
char chr;
|
|
|
|
while ((chr = fgetc(fp)) != EOF) {
|
|
if (chr != '\n') {
|
|
countChr++;
|
|
}
|
|
}
|
|
|
|
fclose(fp);
|
|
} else {
|
|
return -1;
|
|
}
|
|
|
|
return countChr;
|
|
}
|
|
|
|
void copiaFile(const char * nomeFileSorgente, const char * nomeFileDestinazione) {
|
|
FILE * fr = fopen(nomeFileSorgente, "rt");
|
|
|
|
if (fr != NULL) {
|
|
FILE * fw = fopen(nomeFileDestinazione, "wt");
|
|
|
|
if (fw != NULL) {
|
|
char chr;
|
|
|
|
while ((chr = fgetc(fr)) != EOF) {
|
|
fputc(chr, fw);
|
|
}
|
|
|
|
fclose(fw);
|
|
} else {
|
|
perror("Error");
|
|
}
|
|
|
|
fclose(fr);
|
|
} else {
|
|
perror("Error");
|
|
}
|
|
} |