Pascal/Turbo Pascal - Problema en creacion de Archivos

 
Vista:
sin imagen de perfil

Problema en creacion de Archivos

Publicado por Maximiliano (1 intervención) el 16/11/2015 21:13:00
Hola gente de la pagina!

Me presento, me llamo Maximiliano Barconte y estoy en 1er año de Ingenieria Informatica.

El tema es este, NO SÉ como guardar una matriz en un archivo. Tenemos que presentar un Trabajo Practico a fin de mes, es una pavada el ejercicio, la logica la veo facil, la tengo hecha mentalmente, el problema es que no sé como manejar los archivos, ni crearlos (principalmente crearlos / definirlos ).

No les pido que me den una clase, pero algun codigo intuitivo como ejemplo me ayudaria mucho.

(use el buscador pero me canse de entrar a temas, ninguno explica algo tan basico jaja)


El ejercicio es el siguiente:

1. Lavadero de autos: debe registrar los distintos vehiculos qur ingresaron (archivo vehiculo), debe registrar los lavados que se hicieron a cada vehiculo segun tipo de lavados(archivo movimiento), consideramos quesolo atendemos a clientes(archivo_cliente), consultas varias(por lavado, vehiculo, total recaudado, total recuadado segun tipo de vehiculos, realizar algun ordenamiento,menejo de algun fecha) y amb de todo.


no es dificil, pero algo extenso, el problema es que no pude ni comenzar, por el problema ya mensionado.



DESDE YA MUCHISIMAS GRACIAS!
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder

Problema en creacion de Archivos

Publicado por Agustin Guerra (5 intervenciones) el 17/11/2015 19:33:04
Hola, soy medio pete en esto de la programacion, estoy en 1ero como vos, y mientras espero que me respondan las consultas que subi ayer, me puse a leer esto.
Yo solo he probado manejar un tipo de archivo, que son de texto, adentro contienen registros, y se accede a ellos por acceso directo.

te ejemplifico, vamos a probar crear el primer archivo. archivo_vehiculo

Create una carpeta en el disco C, por ejemplo (pongo las barras al reves porque estoy en una net y no las encuentro) C:/dato

En la carpeta crea un archivo que se llame archivo_vehiculo.txt

Con este archivo creado te vas al compilador.

En la seccion TYPE creas un tipo registro, que va a ser los tipos que va a contener tu archivo_vehiculo, por ejemplo

vehiculo=record;
campo1:tipo1;
campo2:tipo2
end;

(los campos podrian ser marca, modelo, color, patente, etc)

En la misma seccion type creas el (archivo:

archivo_vehiculo = file of vehiculo; (NOMBRE DEL ARCHIVO que contendra registros de tipo vehiculo)

-----------------------------------------------------------------------------------------

Con todo esto creado ya podes empezar a manejar el archivo, para ello los comandos basicos son:

Siempre antes de empezar a trabajar con un archivo:

*assign(arch_vehic, C:/dato/archivo_vehiculo.txt); asigna el archivo fisico a una variable de nombre "arch_vehic", ahora cuando escribas el nombre de la variable, te vas a estar refiriendo a dicho archivo)

*reset (arch_vehic); abre el archivo para trabajar en el.

Ahora para trabajar con el mismo, podes usar 2 comandos:

seek(arch_vehic, 0); apunta al primer registro del archivo, siempre 0 es el primero y si N es la cantidad de registros, el ultimo es N-1
otra forma de usar seek puede ser:
seek(arch_vehic, filesize(arch_vehic)); la funcion filesize devuelve el tamaño del archivo, y lo posiciona un registro despues de la ultima posicion, para crear un nuevo elemento al final. Esta indicacion debe darse siempre que quieras cargar algo al final del archivo.

read(arch_vehic, vehiculo); Leera el registro tipo vehiculo del arch_vehic, si no le decis donde posicionarte previamente, se posiciona por defecto al principio del archivo

Una funcion muy util para recorrer el archivo es EOF (End Of File) que tiene un valor booleano. 0 es que no llego al final del archivo, 1 el reciproco. Por ejemplo:

while NOT EOF de begin
read(archiv_vehic, vehiculo);
vehiculo.campo1:=' ';
write(archiv_vehic, vehiculo);
end;

El mientras anterior, abre uno a uno los registros y coloca un espacio en blanco en campo1.

write(archiv_vehic, vehiculo), si bien es un comando ya conocido, cuando lee esos parametros se da cuenta que esta siendo usado para archivos. Lo que hace es escribir la informacion que le acabamos de dar al registro (si no hacemos esto la informacion no se guarda)

Por ultimo usamos
close(archiv_vehic); para cerrar el archivo.

-------------------------------------------------------------------------------------------------------
Como soy medio pelmazo para expresarme por ahi no me entiendas, te copio y pego un pedazo de mi programa documentado asi lo ves mejor. abrazo

El siguiente procedimiento sirve para cargar libros en un archivo. El registro de tipo libro contiene los campos ISBN, TITULO, AUTOR, EDITORIAL Y STOCK.
El primer dato que pido es el ISBN y realizo una busqueda en el archivo (fijate que no tengo que ir incrementando a apuntando para que pase al siguiente registro, como si hay que hacerlo con las listas. Aca pasa automaticamente), si lo encuentro no permito cargarlo nuevamente. Si no lo encuentro procedo a cargar los datos.
Cuando todo termina, recien ahi, antes de salir del procedimiento cierro el archivo.

procedure cargar_libro(var archiv: archivo_lib); //Los archivos SIEMPRE se pasan por referencia, no por copia//
var
lib:libro;
enc:boolean;
isbnaux:string;
begin
enc:=false;
clrscr;
cabecera;
textcolor(RED);
writeln('');
writeln(' ---------------------CARGA DE LIBRO---------------------');
textcolor(black);
writeln('');
writeln(' Ingrese los datos del libro que desea cargar al sistema: ');
writeln('');

assign(archiv,'c:\dato\libro.txt'); //Asigna el archivo libro.txt a la variable archiv//
reset(archiv); //Abre el archivo//
textcolor(black);

write(' ISBN: '); //Recibe el ISBN por teclado, y lo busca//
textcolor(white); readln(isbnaux); //Si ya se encuentra cargado en el sistema//
while ((not EOF(archiv)) and (not enc)) do //lo informa y no permite cargarlo. De lo //
begin //contrario continua con la carga//
read(archiv,lib);
if (isbnaux=lib.isbn) then
begin
enc:=true;
clrscr;
cabecera;
textcolor(RED);
writeln('');
writeln(' ------------------------ATENCION------------------------');
writeln('');
textcolor(black);
writeln(' El libro "',lib.titulo,'" ya se encuentra cargado en el sistema');
writeln('');
writeln('');
writeln('');

textcolor(06);
write(' Presione cualquier tecla para volver al menu principal');
readkey;

end;

end;
if (not enc) then begin //Si no encontro isbn//
seek(archiv,filesize(archiv)); //se posiciona al final del archivo y escribe//
lib.isbn:=isbnaux;

textcolor(black); write(' Titulo: '); textcolor(white); readln(lib.titulo);
textcolor(black); write(' Autor: ');textcolor(white); readln(lib.autor);
textcolor(black); write(' Editorial: ');textcolor(white); readln(lib.editorial);
textcolor(black); write(' Stock: ');textcolor(white); readln(lib.stock);


write(archiv, lib); //La funcion write escribe el contenido de lib en archiv//


clrscr; //Limpia pantalla y muestra mensaje de exito//
cabecera;
textcolor(RED);
writeln('');
writeln(' -------------------------EXITO--------------------------');
writeln('');
textcolor(black);
writeln(' El libro "', lib.titulo,'" fue correctamente cargado al sistema');
writeln('');
writeln('');
writeln('');

textcolor(06);
write(' Presione cualquier tecla para volver al menu principal');
readkey;

end;
close(archiv); //Cierra el archivo//
end;
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
1
Comentar

Problema en creacion de Archivos

Publicado por Agustin Guerra (5 intervenciones) el 17/11/2015 19:39:02
Bueno, te dije lo que se de archivos pero no respondi a tu consulta de como guardar una matriz en un archivo.
Podes guardar la matriz completa, supongamos que algo asi

Creas y definis el tipo MATRIZ.
Creas y definis en registro, y adentro un unico campo que contenga tipo de dato MATRIZ.
Creas el archivo que contiene el tipo de registro creado previamente

Si vos queres guardar uno a uno los elementos de la matriz, tendrias que hacer una rutina que recorra la matriz valor por valor, y copie cada uno en un registro distinto del archivo. En este caso el registro, en lugar de guardar en el campo el tipo de matriz, guarda el tipo de elemento que contiene la matriz (Si la matriz tiene numeros enteros, el campo del registro seria campo:integer; en lugar de campo:matriz;)
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
1
Comentar

Problema en creacion de Archivos

Publicado por ramon (2158 intervenciones) el 21/11/2015 11:33:53
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
{Mira esto}
 
 program veiculos;
  uses
    crt;
  const
     elserv : array[1..4] of string[8] = (
     'Sencillo','Medio','Alto','Especial');
     archivo = 'datos.dat';
  type
    string40 = string[40];
    string10 = string[10];
    cliente = record
         marca : string40;
         matri : string10;
         servi : array[1..20] of integer;
         inpor : array[1..20] of real;
         entra : integer;
       end;
 
 
   var
     f : file of cliente;
     dato : cliente;
     guarda : boolean;
 
     procedure guardar_datos(bb : boolean; rg : cliente);
     begin
        if bb = true then
        begin
           assign(f,archivo);
        {$I-} reset(f); {$I+}
        if ioresult <> 0 then
        begin
           rewrite(f);
           seek(f,0);
           write(f,rg);
           close(f);
        end
     else
        begin
           seek(f,filesize(f));
           write(f,rg);
           close(f);
        end;
      end
   else
        begin
           writeln('   Registro No Guardado Pulse Una Tecla');
           readkey;
        end;
     end;
 
     function existe_cliente(mat : string10) : boolean;
     var
       d, y : longint;
       tem : cliente;
       esta : boolean;
     begin
        for d := 1 to length(mat) do
        mat[d] := upcase(mat[d]);
 
        assign(f,archivo);
        {$I-} reset(f); {$I+}
        if ioresult <> 0 then
        begin
 
        end
      else
        begin
           esta := false;
           for y := 0 to filesize(f) - 1 do
           begin
              seek(f,y);
              read(f,tem);
              for d := 1 to length(tem.matri) do
              tem.matri[d] := upcase(tem.matri[d]);
              if tem.matri = mat then
              begin
              esta := true;
              break;
              end;
           end;
           close(f);
           if esta = true then
           existe_cliente := true
         else
           existe_cliente := false;
        end;
     end;
 
     procedure entradadatos_nuevo_cliente(var d : cliente);
     var
       tec : char;
     begin
        guarda := false;
        clrscr;
        writeln('    ***** Entradas Datos Nuevo Cliente *****');
        writeln('    ----------------------------------');
        writeln;
        with d do
        begin
        entra := 1;
        write('    Coche Marca Y Modelo    : ');
        readln(marca);
        write('    Coche Matricula : ');
        readln(matri);
        if existe_cliente(matri) = true then
        begin
           writeln('   Esta Matricula Ya Existe Pulse Una Tecla');
           readkey;
        end
     else
       begin
        writeln('   Servicios 1 = ',elserv[1],'  2 = ',elserv[2],'  3 = ',
                    elserv[3],'  4 = ',elserv[4]);
        write('    Coche Servicio  : ');
        readln(servi[entra]);
        if servi[entra] < 1 then
        servi[entra] := 1;
        if servi[entra] > 4 then
        servi[entra] := 4;
        write('  El Servicio Fue : ',elserv[servi[entra]]);
        writeln;
        write('    Precio Servicio : ');
        readln(inpor[entra]);
        end;
        writeln('    Ficha Correcta [S/N]');
        repeat
           tec := upcase(readkey);
        until tec in['S','N'];
        clrscr;
        if tec = 'S' then
        begin
           guarda := true;
        end;
      end;
    end;
 
    procedure Presenta_Clientes;
    var
      n, r : longint;
      te : char;
    begin
         assign(f,archivo);
        {$I-} reset(f); {$I+}
        if ioresult <> 0 then
        begin
           writeln('   Error Archivo No Encontrado Pulse Una Tecla');
           readkey;
        end
      else
        begin
           r := 3;
           n := 0;
           writeln('   Visualizacion De Datos');
           writeln;
          repeat
             seek(f,n);
             read(f,dato);
             with dato do
             writeln('  ',marca,'              ',matri,'      ',
             elserv[servi[1]],'    ',inpor[1]:0:2);
             n := n + 1;
             r := r + 1;
             if r > 44 then
             begin
                writeln('    Pulse Una Tecla');
                readkey;
                clrscr;
                writeln('   Visualizacion De Datos');
                writeln;
                r := 3;
             end;
          until n > filesize(f) - 1;
          close(f);
        end;
    end;
 
   procedure nueva_entrada_servicio_cliente;
   var
     matnum : string10;
     k, c : longint;
     harc : cliente;
     tt : char;
   begin
       clrscr;
       writeln('    **** Nuevo Servicio ****');
       writeln;
       write('    Num. Matricula : ');
       readln(matnum);
       for k := 1 to length(matnum) do
       matnum[k] := upcase(matnum[k]);
       assign(f,archivo);
   {$I-} reset(f); {$I+}
        if ioresult <> 0 then
        begin
           writeln('   Error Archivo No Encontrado Pulse Una Tecla');
           readkey;
        end
      else
        begin
           for c := 0 to filesize(f) - 1 do
           begin
              seek(f, c);
              read(f, harc);
              for k := 1 to length(harc.matri) do
              harc.matri[k] := upcase(harc.matri[k]);
              if harc.matri = matnum then
              begin
                harc.entra := harc.entra + 1;
            writeln('   Servicios 1 = ',elserv[1],'  2 = ',elserv[2],'  3 = ',
                        elserv[3],'  4 = ',elserv[4]);
                write('   Servicio : ');
                readln(harc.servi[harc.entra]);
                if harc.servi[harc.entra] < 1 then
                harc.servi[harc.entra] := 1;
                if harc.servi[harc.entra] > 4 then
                harc.servi[harc.entra] := 4;
                write('    Importe Del Servicio : ');
                readln(harc.inpor[harc.entra]);
                writeln;
                writeln('   Datos Correctos [S/N]');
                repeat
                    tt := upcase(readkey);
                until tt in['S','N'];
                if tt = 'S' then
                begin
                   seek(f,c);
                   write(f,harc);
                end;
              end;
           end;
           close(f);
        end;
   end;
 
   procedure presenta_istorial_cliente;
   var
     mat : string10;
     k : integer;
     c : longint;
     harc : cliente;
   begin
      clrscr;
       writeln('    **** Istorial Cliente ****');
       writeln;
       write('    Num. Matricula : ');
       readln(mat);
       for k := 1 to length(mat) do
       mat[k] := upcase(mat[k]);
       assign(f,archivo);
   {$I-} reset(f); {$I+}
        if ioresult <> 0 then
        begin
           writeln('   Error Archivo No Encontrado Pulse Una Tecla');
           readkey;
        end
      else
        begin
           for c := 0 to filesize(f) - 1 do
           begin
              seek(f, c);
              read(f, harc);
              for k := 1 to length(harc.matri) do
              harc.matri[k] := upcase(harc.matri[k]);
              if harc.matri = mat then
              begin
             clrscr;
             writeln('    **** Istorial Cliente Matricula ',mat,' ****');
             writeln('    --------------------------------------------');
             writeln;
             writeln('    Marca = ',harc.marca,'   Matricula = ',harc.matri);
             writeln;
             writeln('    Servicios ');
             writeln('    --------- ');
             writeln;
             for k := 1 to harc.entra do
             writeln('    Servicio = ',elserv[harc.servi[k]],'   Importe = ',
                          harc.inpor[k]:0:2);
                 readkey;
                 break;
              end;
           end;
             close(f);
        end;
   end;
 
   procedure menu;
   var
     salir : boolean;
     ted : char;
     begin
       salir := false;
       repeat
          clrscr;
          writeln('    ******* Menu Jeneral *******');
          writeln;
          writeln('    1 = Entrada Nuevo Cliente');
          writeln('    2 = Presentar Cliente');
          writeln('    3 = Presentar istorial cliente');
          writeln('    4 = Entrada Nuevo Servicio');
          writeln('    5 = Salir');
          writeln;
          writeln('    Elija Opcion');
       repeat
           ted := readkey;
       until ted in['1','2','3','4','5'];
       clrscr;
    case ted of
 '1' : entradadatos_nuevo_cliente(dato);
 '2' : Presenta_Clientes;
 '3' : presenta_istorial_cliente;
 '4' : nueva_entrada_servicio_cliente;
 '5' : salir := true;
    end;
     until salir = true;
     end;
 
 
 
 
  begin
     menu;
  end.
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
2
Comentar