archivos

 ARCHIVOS EN C++
MANEJO BASICO ARCHIVOS
#include<fstream.h>
#include<iostream.h>
#include<stdlib.h>
#include<iomanip.h>
#include<conio.h>
void grabar();
void recuperar();
void modificar();
void main()
       {int opc;

       for(;;){
         cout<<"\t =================="<<endl;
         cout<<setw(20)<<"Grabar 1 "<<endl;
         cout<<setw(20)<<"Recuperar 2 "<<endl;
         cout<<setw(20)<<"Modificar 3 "<<endl;
         cout<<setw(20)<<"Salir 4 "<<endl;
         cout<<"\t ==================="<<endl;
         cout<<setw(20)<<"ingrese la opcion:";
         cin>>opc;
         switch(opc)
         {
         case 1: grabar();
                 break;
         case 2: recuperar();
                 break;
         case 3:modificar();
                 break;
         case 4: exit(0);
                 break;
         default:cout<<"ingrese la opcion correcta:"<<endl;
           break;
                }
             }
         }
void grabar()
   {char ruta[20];
   char texto[200];
   cout<<"ingrese el texto:";
   cin>>texto;
   cin.getline(texto,201);
   cout<<"ingrese la unidad a grabar:";
   cin>>ruta;

   ofstream fichero(ruta);
   fichero<<texto<<endl;
   fichero<<"Adios"<<endl;
   fichero.close();
   }
void recuperar()
  {char ruta[20];
  fstream fichero;
  char texto[200];
  cout<<"ingrese la ruta:";
  cin>>ruta;
  fichero.open(ruta,ios::in);
  if(fichero.bad())
   {cout<<"error no se encuentra el archivo:";
   }
  else
    {
    fichero>>texto;
    while(!fichero.eof())
    {cout<<texto<<endl;
    fichero>>texto;
    }
    }
fichero.close();
}
void modificar()
     {char ruta[20];
     char texto[200];
     int *a;

     a=&texto[0];
     cout<<"ingrese el texto:";
     cin>>texto;
     cout<<"ingrese la unidad a grabar:";
     cin>>ruta;
     ofstream fichero(ruta);
     fichero<<texto<<endl;
     fichero<<"    "<<endl;
     fichero.close();
     getch();
     }
2 FORMA
#include"iostream.h"
#include"fstream.h"
#include"conio.h"
#include"stdio.h"
void menu();
void grabar();
void recuperar();
void modificar();
void main()
{
    int opcion;
    opcion=0;
    while (opcion!=4)
        {
            menu();
                cin>>opcion;
                    switch(opcion)
                            {
                                case 1:
                                            grabar();
                                            break;
                                case 2:
                                            recuperar();
                                            break;
                                case 3:
                                            modificar();
                                            break;
                                case 4:
                                            cout<<"Hasta la vista baby:";
                                            break;
                                            default: cout<<"Ingrese numeros dentro del rango";
                            }
            }
}
void menu()
    {
    clrscr();
    cout<<"\t\t MENU DE OPCIONES"<<endl;
    cout<<"\t1. Grabar"<<endl;
    cout<<"\t2. Recuperar"<<endl;
    cout<<"\t3. Modificar"<<endl;
    cout<<"\t4. salir"<<endl;
    cout<<"\tElija Opcion: ";
    }
void grabar()
{
    char ruta[40],texto[200];
   cout<<"Ingrese el texto a almacenar"<<endl;
    gets(texto);
    cout<<" Ingrese la direccion a grabar : ";
    cin>>ruta;
    ofstream fichero(ruta);
    fichero<<texto<<endl;
    fichero.close();
}
void recuperar()
{
    char ruta[20];
    fstream fichero;
    cout<<"Ingrese la unidad a grabar: ";
    gets(ruta);
    char texto[200];
    fichero.open(ruta,ios::in);
    fichero>>texto;

        while(!fichero.eof())
            {
                cout<<texto<<endl;
                fichero>>texto;
            }
    fichero.close();
}
void modificar()
{
    char ruta[40],texto[200];
    cout<<"Ingrese nuevo texto:"<<endl;
    gets(texto);
    FILE *archdisco;
    cout<<"Ingrese la ruta donde guardo el archivo:"<<endl;
    gets(ruta);
    archdisco=fopen(ruta,"a");
    fwrite(&texto ,sizeof(texto) ,1,archdisco);
    fclose(archdisco);
    getchar();
}
3 FORMA
#include <fstream.h>
#include <stdlib.h>
#include "string.h"
#include "conio.h"
#include "stdio.h"
#include <iostream.h>
#include "conio.h"

struct datos
{
  int  codigo;
  char nombre[50];
  char apellidop[100];
  char apellidom[100] ;
  char carrera[100];
  char semestre[20];
  int valido;       //valido=1->si existe        valido=0->no existe
  int valido2;  //mira si el registro es correcto... siempre sera igual a 1706887114
};

int menu()
{
  clrscr ();
  int n=0;
  system("cls");
  cout<<endl<<endl;
  cout<<"                 ==========================================="<<endl;
  cout<<"                 ||            AGENDA PERSONAL            ||"<<endl;
  cout<<"                 ==========================================="<<endl;
  cout<<"                 ||      1. AGREGAR NUEVO REGISTRO        ||"<<endl;
  cout<<"                 ||      2. BUSCAR REGISTRO               ||"<<endl;
  cout<<"                 ||      3. MOSTRAR TODOS LOS REGISTROS   ||"<<endl;
  cout<<"                 ||      4. GUARDAR UNA COPIA             ||"<<endl;
  cout<<"                 ||      5. LEER REGISTRO                 ||"<<endl;
  cout<<"                 ||      6. SALIR                         ||"<<endl;
  cout<<"                 ==========================================="<<endl<<endl;
  while ((n<1) || (n>6))
    { cout<<"          Introduce un numero de las opciones listadas arriba [1-6]: "; cin>>n; }
    cout<<endl;
  return n;
}

void agregar(struct datos d)
{
  char na='s';        //na=preguntar si kiere nuevo registro
  while (na=='s')
    {
    char nn='x';  //nn=verificacion para agregar el registro
    system ("cls"); //borramos pantalla
    //guardamos los datos temporalmente en el struct
    cout<<"codigo: "; cin>>d.codigo;
    cout<<"Nombre: "; cin>> d.nombre;
    cout<<"apellido paterno: ";cin>>d.apellidop;
    cout<<"apellido materno: ";cin>>d.apellidom;
    cout<<"Carrera Profecional: "; cin>> d.carrera;
    cout<<"Semestre: "; cin>> d.semestre; cout<<endl;
    d.valido=1;   //decimos ke el registro si existe
    d.valido2=1706887114; //con esto garantizamos ke es uno de nuestros registros

    //verificamos si kiere agregar el nuevo registro
    while ((nn!='s') && (nn!='n'))
      { cout<<endl<<"Deseas agregar el nuevo registro? [s-n]: "; cin>>nn; }

    //agregamos
    if (nn=='s')
      {
       ofstream reg("D:/alumnos.txt", ios::app | ios::binary); //activamos el archivo en modo de escritura  tomando en cuenta el parametro "app" para agregar en la ultima posicion del archivo
       if(!reg)                         //si no se pudo abrir el archivo
     { cout <<"No se puede abrir el fichero."; }
       reg.seekp(0, ios::end); // Colocar el cursor al final del archivo
       reg.write((char *) &d, sizeof(d));  //escribimos el nuevo registro
       reg.close();  //cerramos el archivo
       cout<<endl<<"Registro agregado exitosamente"<<endl;
       system("pause");
      }
    else
      {
       //borramos los datos temporales del struct
       strcpy(d.nombre,"");
       d.codigo=0;
       d.apellidop;
       d.apellidom;
       strcpy(d.carrera,"");
       strcpy(d.semestre,"");
       d.valido=0;
       d.valido2=0;
       cout<<endl<<"El Registro NO fue agregado"<<endl;
       system("pause");
      }
    na='x';
    while ((na!='s') && (na!='n'))
      { cout<<endl<<endl<<"Deseas agregar un registro nuevo? [s-n]: "; cin>>na; } //la validacion se hace en el while inicial
  }//endwhile
}

void modificar(struct datos d, int nm)
{
   char nnm='x';
   system ("cls"); //borramos pantalla
   //guardamos los datos temporalmente en el struct
   cout<<"codigo: "; cin>>d.codigo;
   cout<<"Nombre: "; cin>> d.nombre;
   cout<<"apellido paterno: ";cin>>d.apellidop;
   cout<<"apellido materno: ";cin>>d.apellidom;
   cout<<"Carrera Profecional: "; cin>> d.carrera;
   cout<<"Semestre: "; cin>> d.semestre; cout<<endl;
   d.valido=1; //decimos ke si existe
   d.valido2=1706887114;

   //verificamos si kiere modificar el registro
   while ((nnm!='s') && (nnm!='n'))
     { cout<<endl<<"Deseas modificar este registro? [s-n]: "; cin>>nnm; }

   //agregamos
   if (nnm=='s')
     {
      ofstream reg("D:/alumnos.txt", ios::out | ios::binary); //activamos el archivo en modo de escritura  (creamos el objeto 'reg')
      if(!reg)                         //si no se pudo abrir el archivo
    { cout <<"No se puede abrir el fichero."; }
      reg.seekp((nm-1)*sizeof(d));     //colocamos el apuntador en la posicion inicial del registro a modificar
      reg.write((char *) &d, sizeof(d));  //escribimos el nuevo registro
      reg.close();  //cerramos el archivo
      cout<<endl<<"Registro modificado exitosamente"<<endl;
     }
   else
     {
      //borramos los datos temporales del struct
      d.codigo=0;
      strcpy(d.nombre,"");
      d.apellidop;
      d.apellidom;
      strcpy(d.carrera,"");
      strcpy(d.semestre,"");
      d.valido=1;
      d.valido2=0;
      cout<<endl<<"El Registro NO fue modificado"<<endl;
     }
   system("pause");
}

void eliminar(struct datos d, int ne)
{
   system ("cls"); //borramos pantalla
   d.valido=0;   //modificamos "valid0" del struct para decir ke ese registro no sera tomado en cuenta
   d.valido2=1706887114; //agregamos nuestra garantia de registro

   //ahora actualizamos el registro
   ofstream reg("D:/alumnos.txt", ios::out | ios::binary); //activamos el archivo en modo de escritura  (creamos el objeto 'reg')
   if(!reg)                         //si no se pudo abrir el archivo
      { cout <<"No se puede abrir el fichero."<<endl; system("pause");}
   reg.seekp((ne-1)*sizeof(d));     //colocamos el apuntador en la posicion inicial del registro a modificar
   reg.write((char *) &d, sizeof(d));  //escribimos el nuevo registro
   reg.close();  //cerramos el archivo
   cout<<endl<<"Registro eliminado"<<endl;
   system("pause");
}

void buscar(struct datos d)
{
  int nb1=0, nb=-2;  //nb1=variable auxiliar para saber si kiere volver a buskar o salir  nb=variable ke guarda el #de registro buskado
  while (nb1<4)
    {
    if (nb1==2)
      { modificar(d, nb); }
    else
      {
       if (nb1==3)
     { eliminar(d, nb); }
      }
    system("cls"); //borramos pantalla
    int nb=-2;
    while (nb<0)
      { cout<<"Introduce el registro a buscar [0 para salir]: "; cin>>nb; }
    if (nb!=0) //si kiere buskar...
      {
      ifstream reg("D:/alumnos.txt", ios::in | ios::binary);      //activa el archivo en modo de lectura (creamos el objeto 'reg')
      reg.seekg((nb-1)*sizeof(d));     //colocamos el apuntador en la posicion inicial del registro encontrado
      reg.read((char *) &d, sizeof d);        //leemos el registro encontrado
      //verificamos que el registro es correcto
      if ((d.valido==1) && (d.valido2==1706887114))
    {
    cout<<endl<<endl<<"--------Registro encontrado--------"<<endl;
    cout<<"codigo: "<<d.codigo<<endl<<"Nombre: "<<d.nombre<<endl<<"Apellido Paterno: "<<d.apellidop<<endl<<"Apellido Materno: "<<d.apellidom<<endl<<"Carrera Profecional: "<<d.carrera<<endl<<"Semestre: "<<d.semestre<<endl<<endl;
    cout<<endl;    //imprimimos menu de opciones
    cout<<"                 ================================"<<endl;
    cout<<"                 ||          OPCIONES          ||"<<endl;
    cout<<"                 ================================"<<endl;
    cout<<"                 ||    1. NUEVA BUSQUEDA       ||"<<endl;
    cout<<"                 ||    2. MODIFICAR REGISTRO   ||"<<endl;
    cout<<"                 ||    3. ELIMINAR REGISTRO    ||"<<endl;
    cout<<"                 ||    4. SALIR                ||"<<endl;
    cout<<"                 ================================"<<endl<<endl;
    nb1=0;
    while ((nb1<1) || (nb1>4))
      { cout<<"     Introduce un numero de las opciones listadas arriba [1-4]: "; cin>>nb1; }
    cout<<endl;
    }//endif ((d.valido==1) && (d.valido2==1706887114))
      else //si el registro encontrado no es correcto
    {
     cout<<endl<<"El registro buscado no existe"<<endl;
     system("pause");
     nb1=1;
    }
      }//endif (nb!=0)
    else     //si ya se kiere salir
      { nb1=4; } //igualamos la bandera a 4 para ke se salga
    } //endwhile
}

void mostrar(struct datos d)
{
  int nb11=0,con=0,nme=0,bandera=0;  //nb1=variable auxiliar para saber si kiere volver a buskar o salir  nb=variable ke guarda el #de registro buskado
  while (nb11<3)
    {
    if (nb11==1)
      { modificar(d, nme); }
    else
      {
       if (nb11==2)
     { eliminar(d, nme); }
      }
    system("cls"); //borramos pantalla
    ifstream reg("D:/alumnos.txt", ios::in | ios::binary);      //activa el archivo en modo de lectura (creamos el objeto 'reg')
    con=0;
    bandera=0;
    while (reg && !reg.eof())
      {
       reg.seekg((con)*sizeof(d));     //colocamos el apuntador en la posicion inicial del registro encontrado
       reg.read((char *) &d, sizeof d);        //leemos el registro encontrado
       con++; //incrementamos contador del registro
       //verificamos que el registro es correcto
       if ((d.valido==1) && (d.valido2==1706887114))
     {
     bandera=1;
     cout<<endl<<"--------Registro "<<con<<"--------"<<endl;
     cout<<"codigo: "<<d.codigo<<endl<<"Nombre: "<<d.nombre<<endl<<"Apellido Paterno: "<<d.apellidop<<endl<<"Apellido Materno: "<<d.apellidom<<endl<<"Carrera Profecional: "<<d.carrera<<endl<<"Semestre: "<<d.semestre<<endl<<endl;
     }//endif
      }//endwhile
    if (bandera==1)
     {
      cout<<endl<<endl;    //imprimimos menu de opciones
      cout<<"                 ================================"<<endl;
      cout<<"                 ||          OPCIONES          ||"<<endl;
      cout<<"                 ================================"<<endl;
      cout<<"                 ||    1. MODIFICAR REGISTRO   ||"<<endl;
      cout<<"                 ||    2. ELIMINAR REGISTRO    ||"<<endl;
      cout<<"                 ||    3. SALIR                ||"<<endl;
      cout<<"                 ================================"<<endl<<endl;
      nb11=0;
      //preguntamos por ke opcion kiere realizar
      while ((nb11<1) || (nb11>3))
    { cout<<"     Introduce un numero de las opciones listadas arriba [1-4]: "; cin>>nb11; }
      nme=0;
      while ((nme<1) && (nb11<3))
    { cout<<"     Introduce el numero del registro: "; cin>>nme; }
     }//endif bandera=1
    else
      { cout<<"No existen registros!"<<endl; system("pause"); nb11=3;}
    } //endwhile
}
void guardarco(struct datos d)
{
     ifstream origen("D:/alumnos.txt");
    char linea[128];
    char f,cade[128]="E:/copia.txt";
    int c;
    ifstream archivo("E:/copia.txt", ios::noreplace,ios::out );

    long contador = 0L;

   if(origen.fail())
    cerr << "Error al abrir el archivo registro.txt" << endl;
    else
    {
    ofstream destino("E:/Copia.txt", ios::noreplace);
    if(destino.fail())
    cerr << "Error al crear el archivo \"Copia.txt\"" << endl;
    else
    {
        while(!origen.eof())
        {
        origen.getline(linea, sizeof(linea));
        if(origen.good()) // si lectura ok y
        if(origen.eof())  // si eof, -> termina
        exit(1);          // el programa
        else
        destino << linea << endl;
        if(destino.fail())
        {
            cerr << "Fallo de escritura en archivo"<< endl;
            exit(1);
        }
        }
    }
    destino.close();
    }
    origen.close();

getch();
}
void leerre(struct datos d)
{


     ifstream archivo("E:/copia.txt", ios::noreplace);
    char linea[128];
    long contador = 0L;

    if(archivo.fail())
    cerr << "Error al abrir el archivo alumnos.txt" << endl;
    else
    while(!archivo.eof())
    {
    archivo.getline(linea, sizeof(linea));
    cout << linea << endl;
    if((++contador % 24)==0)
    {
        cout << "CONTINUA...";
        cin.get();
    }
    }
    archivo.close();


 getch();


}

int main()
{
  struct datos d;
  int x=0;
  fstream ("D:/alumnos.txt", ios::out | ios::in | ios::binary);   //creamos el archivo
  int n=0,band=0;
  while (band==0)
    {
     n=menu();
     switch (n)
       {
    case 1: agregar(d); break;
    case 2: buscar(d); break;
    case 3: mostrar(d); break;
    case 6: band=1; break;
    case 4: guardarco(d);break;
    case 5: leerre(d);break;
       }
    }
  system("PAUSE");
  return 0;
}
4 FORMA
#include"iostream.h"
#include"fstream.h"
#include"conio.h"
#include"stdio.h"
void menu();
void grabar();
void recuperar();
void modificar();
void main()
{
    int opcion;
    opcion=0;
    while (opcion!=4){
            menu();
                cin>>opcion;
                    switch(opcion){
                    case 1:
                    grabar();
                    break;
                    case 2:
                    recuperar();
                    break;
                    case 3:
                    modificar();
                    break;
                    case 4:
                    cout<<"Salio del Programa";
                    break;
                    default: cout<<"Ingrese numeros dentro del rango";
                    }
            }
}
void menu()
    {
    clrscr();
    cout<<" MENU DE OPCIONES"<<endl;
    cout<<"[1] INICIAR"<<endl;
    cout<<"[2] VER"<<endl;
    cout<<"[3] Modificar"<<endl;
    cout<<"[4] salir"<<endl;
    cout<<"elija Opcion: ";
    }
void grabar(){
    char a[50],txt[20],txt2[20];
    cout<<"bienvenido al programa fichero"<<endl;
    cout<<"Ingrese el texto que desea almacenar"<<endl;
    gets(txt);
    cout<<"ingrese : ";gets(txt2);
    cout<<" Ingrese la direccion a grabar : ";
    cin>>a;
    ofstream fichero(a);
    fichero<<txt<<endl;
   fichero<<txt2<<endl;
    fichero.close();
}
void recuperar(){
    char a[50];
    fstream fichero;
    cout<<"Ingrese la direccion del archivo: ";
    gets(a);
    char texto[200];
    fichero.open(a,ios::in);
    fichero>>texto;
    while(!fichero.eof()){
    cout<<texto<<endl;
    fichero>>texto;
    }
    fichero.close();
}
void modificar(){
    char a[40],txt[20],txt2[20];
    cout<<"Ingrese que desea registrar:"<<endl;
    gets(txt);
    cout<<"ingrese : "<<endl;
    gets(txt2);
    FILE *archdisco;
    cout<<"Ingrese la ruta donde guardo el archivo:"<<endl;
    gets(a);
   cout<<"datos guardados"<<endl;
    archdisco=fopen(a,"a");
    fwrite(&txt ,sizeof(txt) ,1,archdisco);
    fwrite(&txt2 ,sizeof(txt2) ,1,archdisco);
    fclose(archdisco);
    getchar();
}
5 FORMA
#include<iostream.h>
#include<conio.h>
#include<fstream.h>
#include<stdlib.h>
#include<iomanip.h>
void grabar();
void recuperar();
void modificar();
void main()
           {
            int opc;
            for(;;)
               {
                cout<<"\t\t\t************FICHEROS************"<<endl;
                cout<<"   "<<endl;
                cout<<setw(35)<<"\t\t 1 GRABAR "<<endl;
                cout<<setw(35)<<"\t\t 2 RECUPERAR "<<endl;
                cout<<setw(35)<<"\t\t 3 MODIFICAR "<<endl;
                cout<<setw(35)<<"\t 4 SALIR "<<endl;
                cout<<"INGRESE LA OPCION: ";
                cin>>opc;
                switch(opc)
                {
                 case 1:grabar();break;
                 case 2:recuperar();break;
                 case 3:modificar();break;
                 case 4:exit(0);break;
                 default:cout<<"INGRESE LA OPCION CORRECTA: "<<endl;break;
                }
               }
           }
void grabar()
            {
             char ruta[20];
             char texto[200];
             cout<<"INGRESE EL TEXTO: ";
             cin>>texto;
             //cin.getline(texto,201);
             cout<<"INGRESE LA UNIDAD A GRABAR: ";
             cin>>ruta;
             ofstream fichero(ruta);
             fichero<<texto<<endl;
             fichero<<"ADIOS"<<endl;
             fichero.close();
            }
void recuperar()
                {
                 char ruta[20];
                 fstream fichero;
                 char texto[200];
                 cout<<"INGRESE LA RUTA: ";
                 cin>>ruta;
                 fichero.open(ruta,ios::in);
                 if(fichero.bad())
                    {
                     cout<<"ERROR NO SE ENCUENTRA EL ARCHIVO";
                    }
                 else
                 {
                  fichero>>texto;
                  while(!fichero.eof())
                       {
                        cout<<texto<<endl;
                        fichero>>texto;
                       }
                   }
                  fichero.close();
                }
void modificar()
                {
                 char ruta[20];
                 fstream fichero;
                 char texto[200];
                 cout<<"INGRESE LA RUTA: ";
                 cin>>ruta;
                 fichero.open(ruta,ios::in);
                 if(fichero.bad())
                    {
                     cout<<"ERROR NO SE ENCUENTRA EL ARCHIVO";
                    }
                 else
                 {
                  fichero>>texto;
                  while(!fichero.eof())
                       {
                        cout<<texto<<endl;
                        fichero>>texto;
                        cout<<"INGRESE EL TEXTO A AGREGAR: ";
                        cout<<"\n";
                        cin>>texto;
                        cout<<"INGRESE LA UNIDAD A GRABAR: ";
                        cin>>ruta;
                        ofstream fichero(ruta,ios::app);
                        fichero<<texto<<endl;
                       }
                   }

                 fichero.close();
                }






1 comentario: