Grupo
Manejo de Archivos en C++
Ojetivo
1. Solicite al usuario que introduzca el nombre del archivo que se va a eliminar.
2. Utilice la función `remove()` para intentar eliminar el archivo.
3. Compruebe el valor de retorno de `remove()` para determinar si la operación se realizó correctamente.
4. Muestre un mensaje indicando si el archivo se eliminó o si se produjo un error.
Cree un programa que elimine un archivo específico.
Ejemplo de Código C++
Mostrar Código C++
#include <iostream> // For input and output
#include <cstdio> // For using the remove() function
#include <string> // For using the string class
using namespace std;
int main() {
string filename; // Variable to store the name of the file to delete
// Ask the user to enter the filename
cout << "Enter the name of the file to delete: ";
getline(cin, filename); // Read the full filename from user input
// Attempt to delete the file using the remove() function
if (remove(filename.c_str()) == 0) {
// If remove() returns 0, the file was successfully deleted
cout << "File deleted successfully." << endl;
} else {
// If remove() returns a non-zero value, an error occurred
cout << "Error: Unable to delete the file. It may not exist." << endl;
}
return 0; // End of program
}
Salida
//Output Example:
Enter the name of the file to delete: example.txt
File deleted successfully.
//Or in case of error:
Enter the name of the file to delete: missing.txt
Error: Unable to delete the file. It may not exist.
Comparte este ejercicio C++