You are on page 1of 8

ARCHIVOS EN C++

PARA LLEVAR A CABO EL PROCESAMIENTO DE ARCHIVOS EN C++, SE DEBEN INCLUIR LOS ARCHIVOS DE ENCABEZADO <iostream> y <fstream>. EL ENCABEZADO <fstream> INCLUYE LAS DEFINICIONES PARA LAS PLANTILLAS DE CLASES DE FLUJOS basic_ifstream (PARA OPERACIONES DE ENTRADA Y SALIDA CON ARCHIVOS). CADA PLANTILLA DE CLASE TIENE UNA ESPECIALIZACION DE PLANTILLA PREDEFINIDA QUE PERMITE LAS OPERACIONES DE E/S CON VALORES CHAR, ADEMAS LA BIBLIOTECA <fstream> proporciona ALIAS TYPEDEF PARA ESTAS ESPECIALIZACIONES DE PLANTILLA. POR EJEMPLO, LA DEFINICION typedef ifstream REPRESENTA UNA ESPECIALIZACION DE basic_ifstream que permite LA ENTRA DE VALORES CHAR DESDE UN ARCHIVO. DE MANERA SIMILAR typedef ofstream representa UNA ESPECIALIZACIN DE basic_ofstream que permite ENVIAR VALORES CHAR A ARCHIVOS. Typedef stream REPRESENTA UNA ESPECIALIZACION DE basic_ofstream QUE PERMITE INTRODUCIR VALORES CHAR DESDE (Y ENVIARLOS HACIA) ARCHIVOS. PARA ABRIR ARCHIVOS, SE CREAN OBJETOS DE ESTAS ESPECIALIZACIOES DE PLANTILLAS DE FLUJO. ESTAS PLANTILLAS SE DERIVAN DE LAS PLANTILLAS DE CLASES basic_istream, basic_ostream y basic_iostream RESPECTIVAMENTE.

#include <iostream> #include <fstream> using namespace std; int main() { char cadena[128]; // Crea un fichero de salida ofstream fs("nombre.txt"); // Enviamos una cadena al fichero de salida: fs << "Hola, mundo2. Esta es una prueba de escritura en el archivo TXT" << endl; // Cerrar el fichero, // para luego poder abrirlo para lectura: fs.close(); // Abre un fichero de entrada ifstream fe("nombre.txt"); // Leeremos mediante getline, si lo hiciramos // mediante el operador >> slo leeramos // parte de la cadena: fe.getline(cadena, 128); cout << cadena << endl; cin.get(); return 0; } //archivo1

#include <fstream> #include <iostream> using namespace std; int main() { int i,pos; char mes[][20] = {"Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre"}; char cad[20]; ofstream fsalida("meses.dat", ios::out | ios::binary); // Crear fichero con los nombres de los meses: cout << "Crear archivo de nombres de meses:" << endl; for(i = 0; i < 12; i++) fsalida.write(mes[i], 20); fsalida.close(); ifstream fentrada("meses.dat", ios::in | ios::binary); // Acceso secuencial: cout << "\nAcceso secuencial:" << endl; fentrada.read(cad, 20); do { cout << cad << endl; fentrada.read(cad, 20); } while(!fentrada.eof()); fentrada.clear(); // Acceso aleatorio: cout << "\nAcceso aleatorio:" << endl; for(i = 11; i >= 0; i--) { fentrada.seekg(20*i, ios::beg); fentrada.read(cad, 20); cout << cad << endl; } // Calcular el nmero de elementos // almacenados en un fichero: // ir al final del fichero fentrada.seekg(0, ios::end); // leer la posicin actual pos = fentrada.tellg();

// El nmero de registros es el tamao en // bytes dividido entre el tamao del registro: cout << "\nNmero de registros: " << pos/20 << endl; fentrada.close(); cin.get(); return 0; }

#include <fstream> #include <iostream> using namespace std; int main() { char l; long i, lon; fstream fich("prueba.dat", ios::in | ios::out | ios::trunc | ios::binary); fich << "abracadabra" << flush; fich.seekg(0L, ios::end); lon = fich.tellg(); for(i = 0L; i < lon; i++) { fich.seekg(i, ios::beg); fich.get(l); if(l == 'a') { fich.seekp(i, ios::beg); fich << 'o'; } } cout << "Salida:" << endl; fich.seekg(0L, ios::beg); for(i = 0L; i < lon; i++) { fich.get(l); cout << l; } cout << endl; fich.close(); cin.get();; return 0; }

#include <iostream> using std::cerr; using std::cout; using std::endl; using std::fixed; using std::ios; using std::left; using std::right; using std::showpoint; #include <fstream> // flujo de archivo using std::ifstream; // flujo de archivo de entrada #include <iomanip> using std::setw; using std::setprecision; #include <string> using std::string; #include <cstdlib> using std::exit; // prototipo de la funcin exit void imprimirLinea( int, const string, double ); // prototipo int main() { // el constructor de ifstream abre el archivo ifstream archivoClientesEntrada( "clientes.dat", ios::in ); // sale del programa si ifstream no pudo abrir el archivo if ( !archivoClientesEntrada ) { cerr << "No se pudo abrir el archivo" << endl; exit( 1 ); } // fin de if int cuenta; char nombre[ 30 ]; double saldo; cout << left << setw( 10 ) << "Cuenta" << setw( 13 ) << "Nombre" << "Saldo" << endl << fixed << showpoint; // muestra cada registro en el archivo while ( archivoClientesEntrada >> cuenta >> nombre >> saldo ) imprimirLinea( cuenta, nombre, saldo ); return 0; // el destructor de ifstream cierra el archivo } // fin de main void imprimirLinea( int cuenta, const string nombre, double saldo ) { cout << left << setw( 10 ) << cuenta << setw( 13 ) << nombre << setw( 7 ) << setprecision( 2 ) << right << saldo << endl;

} // fin de la funcin imprimirLinea

#include <fstream> #include <cstring> #include <iostream> using namespace std; struct tipoRegistro { char nombre[32]; int edad; float altura; }; int main() { tipoRegistro pepe; tipoRegistro pepe2; ofstream fsalida("prueba.dat", ios::out | ios::binary); strcpy(pepe.nombre, "Jose Luis"); pepe.edad = 32; pepe.altura = 1.78; fsalida.write(reinterpret_cast<char *>(&pepe), sizeof(tipoRegistro)); fsalida.close(); ifstream fentrada("prueba.dat", ios::in | ios::binary); fentrada.read(reinterpret_cast<char *>(&pepe2), sizeof(tipoRegistro)); cout << pepe2.nombre << endl; cout << pepe2.edad << endl; cout << pepe2.altura <<endl; fentrada.close(); cin.get(); return 0; }

#include <iostream> using std::cerr;

using std::cin; using std::cout; using std::endl; using std::ios; #include <fstream> // flujo de archivo using std::ofstream; // flujo de archivo de salida #include <cstdlib> using std::exit; // prototipo de la funcin exit int main() { // el constructor de ofstream abre el archivo ofstream archivoClientesSalida( "clientes.dat", ios::out ); // sale del programa si no puede crear el archivo if ( !archivoClientesSalida ) // operador ! sobrecargado { cerr << "No se pudo abrir el archivo" << endl; exit( 1 ); } // fin de if cout << "Escriba la cuenta, nombre y saldo." << endl << "Escriba fin de archivo para terminar la entrada.\n? "; int cuenta; char nombre[ 30 ]; double saldo; // lee la cuenta, nombre y saldo de cin, y despus los coloca en el archivo while ( cin >> cuenta >> nombre >> saldo ) { archivoClientesSalida << cuenta << ' ' << nombre << ' ' << saldo << endl; cout << "? "; } // fin de while return 0; // el destructor de ofstream cierra el archivo } // fin de main

MEN PRINCIPAL 1.2.3.4.CREAR ARCHIVO ENVIAR DATOS AL ARCHIVO LEER DATOS DESDE EL ARCHVO SALIR DEL PROGRAMA

OPCIN:_1

Nombre DEL archivo a crear?: EXAMEN1.DAT Regreso al men principal Opcin 2 N ombre del archivo a donde se escribirn sus datos?: EXAMEN1.DAT DAME DATOS: ESTA ES UNA PRUEBA DE ESCRITURA. OPCI+ON 3 LECTURA DEL DATOS DESDE EL ARCHIVO N ombre del archivo a donde se LEERAN sus datos?: EXAMEN1.DAT ESTA ES UNA PRUEBA DE ESCRITURA. OPCIN 4 ESTAMOS SALIENDO DEL PROGRAMA. . . .

rafaelhernandezreyna@yahoo.com.mx

You might also like