File Text – Ejemplo 3

Enunciado

Escribir un procedimiento que busque una clave dentro de un archivo ordenado según un campo clave en forma creciente. Suponer que no hay claves repetidas.

Código

Python

import os
import shelve

def buscar( nomarch, clave ):
    arch = shelve.open( nomarch, flag="r" )

    if clave in arch[ "claves" ]:
        claves = arch[ "claves" ]
        p = claves.index(clave)
        error = False
    else:
        p = -1
        error = True
   
    arch.close()
    return error, p

def main():
    nomarch = input( "Nombre archivo escritura/Write file name: " )
    arch = shelve.open( nomarch, flag="c" )
    c = 0
    claves = []
    mats = []
    noms = []
    r = input( "ENTER para Datos - S para finalizar: " ).upper()
    while ( r!="S" ):
        # Lectura de datos desde teclado
        # Reading data from keyboard
        claves.append( int(input("Orden / Order: ")) )
        mats.append( int(input("matricula / File: ")) )
        noms.append( input("Apellido / Last name: ") )
        c += 1
        r = input( "ENTER para Datos - S para finalizar" ).upper()
    
    # Escribir los datos en el archivo
    # write data to file      
    arch["claves"] = claves
    arch["mats"] = mats
    arch["noms"] = noms
        
    arch.close()

    # Prueba de lectura del archivo directo
    # Direct file reading test
    print()
    arch = shelve.open( nomarch, flag="r" )

    claves = arch["claves"]
    mats = arch["mats"]
    noms = arch["noms"]
    
    print( "\nPos", "Claves".rjust(10),
           "Matriculas".rjust(15),
           "Apellidos".rjust(15) )
    for i in range( len( claves ) ):
        print( str(i).rjust(3),
               str(claves[i]).rjust(10),
               str(mats[i]).rjust(15),
               noms[i].rjust(15) )  
    arch.close()
    
    clave = int( input( "\nIngresar clave a buscar/Enter key to search: " ) )

    s, p = buscar( nomarch, clave )

    if not s:
        print( "\nEncontrado en posicion/", end="" )
        print( "Found in position: ", p )
    else:
        print( "\nNo existe / No exist" )
    
    input( "Presionar/Press Enter to exit " ) 
main()

C++

#include <iostream>
#include <iomanip>
#include <fstream>
using namespace std ;
#include <conio.h>
#include <stdio.h>

struct registro
{
   int clave;
   int mat ;
   char nom[20];
};

void Buscar( string nomarch, int clave, 
	     streampos *p, bool *error )
{
   struct registro r ;
	
   ifstream f( nomarch.c_str(), ios::binary ) ;

   if ( !f )
   {
	cout << "Archivo inexistente/" ;
	cout << "File does not exist" << endl ;
   }
   else
   {
   	f.read( (char*)&r, sizeof(registro) ) ;
      	while( !f.eof() && r.clave!=clave )
	    f.read( (char*)&r, sizeof(registro) ) ;
			
	if ( r.clave==clave )
	{
	    *p = f.tellg() ;
	    *error = true ;
	}
	else
	    *error = false ;
		
	f.close() ;
   }
}

void CrearArchivo (  string nomarch )
{
   struct registro alum ;

   ofstream arch( nomarch.c_str(), ios::binary ) ;
   if (!arch)
   {
       cout << "Archivo inexistente/" ;
       cout << "File does not exist" << endl ;
   }
   else
   {
       cout << "ENTER para Datos -" ;
       cout << " ESC para finalizar" << endl;
       while ( getch() != char(27))
       {
         // Lectura de datos desde teclado
         // Reading data from keyboard
         cout << "Orden / Order: ";	
         cin >> alum.clave;
         cout << "matricula / File: ";
         cin >> alum.mat;
         cout << "Apellido / Last name:";	
         cin >> alum.nom;

         // Escribir los datos en el archivo
         // Write data to file
         arch.write( (char*)&alum, sizeof(registro) ) ; 
       }
       arch.close() ;
   }
}

void LeerArchivo ( string nomarch )
{
   struct registro alum ;

   ifstream arch( nomarch.c_str(), ios::binary ) ;
   if ( !arch )
   {
       cout << "Archivo inexistente/" ;
       cout << "File does not exist" << endl ;
   }
   else
   {
       cout << setw(3) << "Nro" << setw(6) 
	    << "Matr" << setw(11) << "Apellido"<< endl;
       do
       {
	  arch.read( (char*)&alum, sizeof(registro) ) ;
	  if ( arch.good() )
	     cout << alum.clave << setw(10) 
		  << alum.mat << setw(15) 
		  << alum.nom << endl ;
	} while( !arch.eof() ) ;
	arch.close() ;
   }
}

int main()
{
   int clave;
   streampos p ;
   bool s ;
   string nomarch ;
   registro alum ;

   cout << "Nombre archivo lectura/" ,
   cout << "Read file name: " ; 
   cin >> nomarch ;
   CrearArchivo( nomarch ) ;
   LeerArchivo( nomarch ) ;
	
   cout << endl << "Ingresar clave a buscar/" ;
   cout << "Enter key to search: " ; 
   cin >> clave ;
	
   Buscar( nomarch, clave, &p, &s ) ;
   if ( s ) 
   {
	cout << "Encontrado en el registro/" ;
	cout << "Found in the registry: " << p ;
   }
   else cout << "No existe / No exist" ;

   cout << endl ;
   cout << "Presionar/Press Enter to exit " ;
   getch() ;
   return 0 ;
}

Pascal

Program Problema21_5 ;
uses CRT ;
type
    registro = record
                  clave: longint ;
                  mat: integer ;
                  nom: string[20] ;
	       end ;
    archivo = file of registro ;
    tipoClave = integer ;	
var
    arch: archivo ;
    rec: registro ;
    nomarch: string[ 12 ] ;
    nf, clave : integer ;
    s: boolean ;
	
Procedure Buscar( var f : archivo ; clave : TipoClave ; 
		  var numr : integer ; 
                  var error : boolean ) ;
var 
    r: registro ;
begin
    reset( f ) ; error := false ;
    while not eof( f ) and 
	  ( r.clave < clave ) do 
	read( f , r ) ;
    if r.clave = clave 
    then numr := filepos( f ) - 1 
    else error := true
end ;

begin
    ClrScr ;
    write( 'Nombre archivo/File name: ' ) ; 
    readln( nomarch ) ;
    assign( arch , nomarch ) ;
    rewrite( arch ) ;
    write( 'Enter para comenzar o ESC para salir/' ) ;
    writeln( 'Enter to start or ESC to exit' ) ;
    while ReadKey<>#27 do
    begin
	with ( rec ) do
	begin
	    write( 'Orden / orden: ') ; 
	    readln( clave ) ;
	    write( 'Matricula / File: ') ; 
	    readln( mat ) ;
	    write( 'Apellido / Last name: ') ; 
	    readln( nom ) ;
	end;
	write( arch , rec ) ;
	write( 'Enter para comenzar o ' ) ;
        write( 'ESC para salir/' ) ;
	writeln( 'Enter to start or ESC to exit' ) ;
    end ; 
    close( arch ) ; 
    writeln ;

    reset( arch ) ; 
    while not EOF( arch ) do
    begin
	read( arch , rec ) ;
	writeln( rec.clave,'', rec.mat, '', rec.nom ) ;
    end ;
	
    write( 'Ingresar clave a buscar/' ) ;
    write( 'Enter key to search: ') ; 
    readln( clave ) ;
    Buscar( arch, clave, nf, s ) ;
    if ( not s )
    then
	writeln( 'Posicion/Position: ', nf+1 )
    else
	writeln( 'No existe/No exist' ) ;
	
    writeln ;
    writeln( 'Presionar/Press Enter to exit ' ) ;
    readln ;
end.

Diagramas