-
Notifications
You must be signed in to change notification settings - Fork 1
/
informe.tex
1945 lines (1892 loc) · 49.3 KB
/
informe.tex
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
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
\documentclass[a4paper,10pt]{article}
\usepackage[spanish]{babel}
\usepackage[utf8]{inputenc}
\usepackage{booktabs}
\usepackage{hyperref}
\usepackage{fontawesome}
\usepackage{graphicx}
\usepackage{listings}
\usepackage{color}
\usepackage{fancyvrb}
\definecolor{dkgreen}{rgb}{0,0.6,0}
\definecolor{gray}{rgb}{0.5,0.5,0.5}
\definecolor{mauve}{rgb}{0.58,0,0.82}
\lstset{frame=tb,
language=C,
aboveskip=3mm,
belowskip=3mm,
showstringspaces=false,
columns=flexible,
basicstyle={\small\ttfamily},
numbers=none,
numberstyle=\tiny\color{gray},
keywordstyle=\color{blue},
commentstyle=\color{dkgreen},
stringstyle=\color{mauve},
breaklines=true,
breakatwhitespace=true,
tabsize=3
}
\lstset{}
\title{
\includegraphics[width=5cm]{plots/fiuba.png}\\
Infraestructura básica\\
Trabajo Práctico 0\\}
\date{}
\author{}
\begin{document}
\pagenumbering{gobble}
\maketitle
\begin{table}[h!]
\centering
\begin{tabular}{ccc}
\toprule
Apellido y Nombre & Padrón & Correo electrónico \\
\midrule
Blanco, Sebastian & 98539 & [email protected]\\
Lavandeira, Lucas & 98042 & [email protected]\\
Llauró, Manuel Luis & 95736 & [email protected]\\
\bottomrule
\end{tabular}
\end{table}
\texttt{GitHub} \faGithub:
\url{https://github.com/lucaslavandeira/palindrome}
\newpage
\pagenumbering{arabic}
\tableofcontents
\newpage
\section{Introducción}
El objetivo de este trabajo práctico familiarizarse con las herramientas de software que usaremos en los siguientes trabajos, implementando un programa para procesar archivos
de texto por línea de comando: el programa recibirá los archivos o streams de
entrada y salida, y deberá imprimir aquellas palabras del archivo de entrada
(componentes léxicos) que sean palíndromos.
\section{Diseño e implementación}
Para lograr armar el programa se decidió utilizar el método en programación conocido como "divide y conquistaras", dividiendo el problema en una suma de problemas mas chicos que son resueltos por las distintas funciones creadas.
Primero se guardó en un array de char los caracteres que fueron pedidos en el enunciado que formen las palabras, considerando el resto de los caracteres separadores entre palabras. Y junto con este array se creó una función correspondiente la cual contesta si un caracter dado pertenece a una palabra o si es un separador de palabras.
Por otro lado se creó una función para saber si una palabra dada es o no un palíndromo, junto a otra función encargada de leer la palabra del archivo de entrada.
Lo siguiente fue tratar el comportamiento esperado para el modo de uso del programa, como el modo de compilación y las entradas esperadas.
El programa fue desarrollado completamente en entornos GNU/Linux, bajo arquitecturas x86-64, teniendo en cuenta que el programa también debería poder ejecutarse en arquitecturas MIPS. Afortunadamente la simplicidad del programa, y de las herramientas de desarrollo del lenguaje de programación C, permitieron la transición entre arquitecturas sin problemas: el programa se compila y se comporta de la misma manera en ambos casos.
Con la suma de todo esto se logró armar el programa pedido.
\section{Modo de uso}
El ejecutable compilado no tiene dependencias con otros archivos o librerías, y puede moverse y ejecutarse desde cualquier directorio. Al ejecutarse desde una terminal sin argumentos adicionales, leerá de la entrada estándar palabras (es decir, componentes léxicos con caracteres alfanuméricos, y dígitos del 0 al 9), e imprimirá por la salida estándar aquellos que sean palíndromos. Al leer un carácter del final de archivo (\texttt{EOF}), finalizará su ejecución.
El programa, adicionalmente, acepta varios parámetros adicionales (todos opcionales):
\begin{itemize}
\item \texttt{-h}: Muestra en pantalla los parámetros aceptados y finaliza su ejecución
\item \texttt{-V}: Muestra la versión del programa compilado y finaliza su ejecución
\item \texttt{-i <archivo>}: Lee la entrada del programa desde el archivo especificado
\item \texttt{-o <archivo>}: Imprime la salida del programa al archivo especificado
\end{itemize}
El programa tiene dos códigos de salida: 0 en funcionamiento correcto, y 1 en caso de error, causado por la lectura inválida de un archivo de entrada, o escritura inválida del archivo de salida.
\section{Herramientas utilizadas y testing}
El funcionamiento correcto del proyecto se sometió a prueba haciendo uso de varias herramientas propias de los entornos Unix-like, principalmente de \textit{bash}, y de las \textit{coreutils} de GNU, para armar un simple script que busque archivos de entrada en un directorio, y compare los resultados (tanto la escritura de un archivo del parámetro \texttt{-o} como de la salida estándar) con archivos de salida. Para facilitar la compilación del programa (y del informe) se utilizó un simple Makefile. También se usa como compilador el designado por la cátedra, \texttt{gcc}.
\section{Problemas encontrados}
El desarrollo del programa no tuvo mayores inconvenientes, teniendo todos los integrantes experiencia programando en C. Como en todo proyecto, se debe explorar algunas tecnologías en las que uno mismo no está familiarizado, y se tuvo que dedicar un tiempo sustancial al estudio de \textit{bash}, y \LaTeX. La compilación del programa no es ejecutado con la mayor rigurosidad de advertencias debido a la detección de algunas cuando se compila en la plataforma MIPS. Sin embargo, el programa resulta funcionar de la misma manera: todos los casos de prueba pasan correctamente.
\section{Correcciones realizadas}
En esta segunda entrega del trabajo Práctico se soportan la entrada de palabras tan grandes como el archivo que se lee, o si proviene de la entrada estándar se soporta una palabra tan grande como la memoria lo permita.
Además se definió, que dado el caso de si por alguna razón externa al programa, las funciones de la librería de C dan algún error, se finaliza el programa retornando el valor 1.
\section{Casos de prueba}
Se realizaron para el trabajo práctico 6 casos de pruebas distintos para verificar el correcto funcionamiento del código.\\
Para correr las pruebas se creó un archivo \texttt{run\char`_tests.sh}, el cual corre todas las pruebas del directorio "test" (el mismo se lo puede encontrar el git, o en el pendrive del tp).\\
A continuación se presentan las pruebas realizadas:\\
Prueba: "\texttt{help.in}" \\
Argumentos de entrada: -h\\
La salida esperada en "help.out": (vacío)\\
La salida esperada en "help.stdout":
\begin{Verbatim}
Usage:
tp0 -h
tp0 -V
tp0 [options]
Options:
-V, --version Print version and quit.
-h, --help Print this information.
-i, --input Location of the input file.
-o, --output Location of the output file.
Examples:
tp0 -i ~/input -o
\end{Verbatim}
Prueba: "\texttt{invalid\char`_arg.in}" \\
Argumentos de entrada: -invalid\\
La salida esperada en "help.out": (vacío)\\
La salida esperada en "help.stdout":
\begin{Verbatim}
Invalid argument: -invalid
\end{Verbatim}
Prueba: "\texttt{long\char`_help.in}" \\
Argumentos de entrada: --help\\
La salida esperada en "\texttt{long\char`_help.out}": (vacío)\\
La salida esperada en "\texttt{long\char`_help.stdout}":
\begin{Verbatim}
Usage:
tp0 -h
tp0 -V
tp0 [options]
Options:
-V, --version Print version and quit.
-h, --help Print this information.
-i, --input Location of the input file.
-o, --output Location of the output file.
Examples:
tp0 -i ~/input -o
\end{Verbatim}
Prueba: "\texttt{long\char`_palindrome.in}" \\
Argumentos de entrada: \texttt{-i test/long\char`_palindrome.txt -o run.out}\\
Archivo \texttt{test/long\char`_palindrome.txt}: \\
\begin{Verbatim}
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
\end{Verbatim}
La salida esperada en "\texttt{long\char`_palindrome.out}": El mismo archivo\\
La salida esperada en "\texttt{long\char`_palindrome.stdout}": (vacío)\\
Prueba: "\texttt{long\char`_params.in}" \\
Argumentos de entrada: \texttt{--input test/single\char`_character.txt --output run.out}\\
Archivo \texttt{test/single\char`_character.txt}: \\
\begin{Verbatim}
A
\end{Verbatim}
La salida esperada en "\texttt{long\char`_palindrome.out}": A\\
La salida esperada en "\texttt{long\char`_palindrome.stdout}": (vacío)\\
Prueba: "\texttt{long\char`_version.in}" \\
Argumentos de entrada: \texttt{--version}\\
Archivo \texttt{test/single\char`_character.txt}: \\
La salida esperada en "\texttt{long\char`_palindrome.out}": (vacío)\\
La salida esperada en "\texttt{long\char`_palindrome.stdout}": \\
\begin{Verbatim}
tp0: version 0.2
\end{Verbatim}
Prueba: "\texttt{multiple\char`_palindrome.in}" \\
Argumentos de entrada: \texttt{-i test/multiple\char`_palindrome.txt -o run.out}\\
Archivo \texttt{test/multiple\char`_palindrome.txt}: \\
\begin{Verbatim}
Somos los primeros en completar el TP 0.
Ojo que La fecha de entrega del TP0 es el martes 12 de septiembre.
\end{Verbatim}
La salida esperada en "\texttt{multiple\char`_palindrome.out}":\\
\begin{Verbatim}
Somos
0
Ojo
\end{Verbatim}
La salida esperada en "\texttt{multiple\char`_palindrome.stdout}": (vacío)\\
Prueba: "\texttt{no\char`_palindrome.in}" \\
Argumentos de entrada: \texttt{-i test/no\char`_palindrome.txt -o run.out}\\
Archivo \texttt{test/no\char`_palindrome.txt}: \\
\begin{Verbatim}
Somos los primeros en completar el TP 0.
Ojo que La fecha de entrega del TP0 es el martes 12 de septiembre.
\end{Verbatim}
La salida esperada en "\texttt{no\char`_palindrome.out}":\\
\begin{Verbatim}
Somos
0
Ojo
\end{Verbatim}
La salida esperada en "\texttt{no\char`_palindrome.stdout}": (vacío)\\
Prueba: "\texttt{single\char`_character.in}" \\
Argumentos de entrada: \texttt{-i test/single\char`_character.txt -o run.out}\\
Archivo \texttt{test/single\char`_character.txt}: \\
\begin{Verbatim}
A
\end{Verbatim}
La salida esperada en "\texttt{single\char`_character.out}":\\
\begin{Verbatim}
A
\end{Verbatim}
La salida esperada en "\texttt{single\char`_character.stdout}": (vacío)\\
Prueba: "\texttt{underscores.in}" \\
Argumentos de entrada: \texttt{-i test/underscores.txt -o run.out}\\
Archivo \texttt{test/underscores.txt}: \\
\begin{Verbatim}
_a_ -a- a-b_c_b-a
\end{Verbatim}
La salida esperada en "\texttt{underscores.out}":\\
\begin{Verbatim}
_a_
-a-
a-b_c_b-a
\end{Verbatim}
La salida esperada en "\texttt{underscores.stdout}": (vacío)\\
Prueba: "\texttt{numeric.in}" \\
Argumentos de entrada: \texttt{-i test/numeric.txt -o run.out}\\
Archivo \texttt{test/numeric.txt}: \\
\begin{Verbatim}
1
9009
12
000000000000
\end{Verbatim}
La salida esperada en "\texttt{numeric.out}":\\
\begin{Verbatim}
1
9009
000000000000
\end{Verbatim}
La salida esperada en "\texttt{numeric.stdout}": (vacío)\\
Prueba: "\texttt{use\char`_stdout.in}" \\
Argumentos de entrada: \texttt{-i test/multiple\char`_palindrome.txt -o run.out}\\
Archivo \texttt{test/multiple\char`_palindrome.txt}: \\
\begin{Verbatim}
Somos los primeros en completar el TP 0.
Ojo que La fecha de entrega del TP0 es el martes 12 de septiembre.
\end{Verbatim}
La salida esperada en "\texttt{numeric.out}": (vacío)\\
La salida esperada en "\texttt{numeric.stdout}": \\
\begin{Verbatim}
Somos
0
Ojo
\end{Verbatim}
Prueba: "\texttt{version.in}" \\
Argumentos de entrada: \texttt{-V}\\
La salida esperada en "\texttt{numeric.out}": (vacío)\\
La salida esperada en "\texttt{numeric.stdout}": \\
\begin{Verbatim}
tp0: version 0.2
\end{Verbatim}
\section{Archivo \texttt{run\char`_tests.sh}}
\begin{lstlisting}
#!/bin/bash
TEST_DIR=test/
IN=$TEST_DIR/in/
OUT=$TEST_DIR/out/
ERROR=$TEST_DIR/error/
for case in $(ls $ERROR); do
rm $ERROR/$case
done
for case in $(ls $IN); do
ERRORS=false
if [ -e run.out ]; then
rm run.out
fi
if [ -e stdout.tmp ]; then
rm stdout.tmp
fi
filename=$(basename ${case%%.*})
printf "Executing $filename... ";
./tp0 $(cat $IN/$case) >> stdout.tmp
if [ -e run.out ]; then
diff run.out $OUT/$filename.out >> tmp;
if [ $? -ne 0 ]; then
ERRORS=true
fi
fi
diff stdout.tmp $OUT/$filename.stdout >> tmp;
if [ $? -eq 0 ]; then
echo "OK"
else
ERRORS=true
fi
if $ERRORS; then
echo "ERROR"
cat tmp
cp stdout.tmp $ERROR/$filename.error.stdout
if [ -e run.out ]; then
cp run.out $ERROR/$filename.error
fi
fi
done
if [ -e tmp ]; then
rm tmp
fi
if [ -e stdout.tmp ]; then
rm stdout.tmp
fi
\end{lstlisting}
\newpage
\section{Anexo A: Código C}
\begin{lstlisting}
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdbool.h>
#include <stdlib.h>
#include <signal.h>
//-------------------------------------------------------------------
// DEFINITIONS
//-------------------------------------------------------------------
#define ERROR 1
#define SUCCESS 0
#define VERSION "0.2"
const char help_str[] = "Usage:\n"
" tp0 -h\n"
" tp0 -V\n"
" tp0 [options]\n"
"Options:\n"
" -V, --version\tPrint version and quit.\n"
" -h, --help\tPrint this information.\n"
" -i, --input\tLocation of the input file.\n"
" -o, --output\tLocation of the output file.\n"
"Examples:\n"
" tp0 -i ~/input -o\n";
#define SPACE_SIZE 65
#define SPACE_INDEX 123
#define EMPTY (-1)
const char ENTER = '\n';
char space[SPACE_SIZE];
int spaceIndex[SPACE_INDEX];
//-------------------------------------------------------------------
// CHARGE SPACE
//-------------------------------------------------------------------
// Del 97 al 122 estan las letras de a-z
// Del 65 al 90 estan las letras de A-Z
// Del 48 al 57 estan los numeros de 0-9
// '-' es 45
// '_' es 95
void chargeSpace() {
int pos = 0;
for (int i = 0; i < SPACE_INDEX; i++) spaceIndex[i] = EMPTY;
//---------------------------------------------------------------
for (int i = 97; i <= 122; i++) {
space[pos] = (char)i;
spaceIndex[i] = pos;
pos++;
}
//---------------------------------------------------------------
for (int i = 65; i <= 90; i++) {
space[pos] = (char)i;
spaceIndex[i] = pos;
pos++;
}
//---------------------------------------------------------------
for (int i = 48; i <= 57; i++) {
space[pos] = (char)i;
spaceIndex[i] = pos;
pos++;
}
//---------------------------------------------------------------
// incluyo el guion medio
pos++;
space[pos] = '-';
spaceIndex[45] = pos;
//----------------------------------------------------------------
// incluyo el guion bajo
pos++;
space[pos] = '_';
spaceIndex[95] = pos;
}
//--------------------------------------------------------------------
// BELONGS TO SPACE
//--------------------------------------------------------------------
bool belongsToSpace(int aChar) {
if (aChar >= SPACE_INDEX) return false;
return spaceIndex[aChar] != EMPTY;
}
//--------------------------------------------------------------------
// WRITE OUT FILE
//---------------------------------------------------------------------
int writeOutFile(FILE* archIn, long begin, long end, FILE* archOut) {
int c;
if (fseek(archIn, begin, SEEK_SET) < 0) return ERROR;
for (long i = 0; i < (end - begin); i++) {
if (fread((char*)(&c), sizeof(char), 1, archIn) <= 0) return ERROR;
if (fwrite((char*)(&c), sizeof(char), 1, archOut) <= 0) return ERROR;
}
if (fwrite((char*)(&ENTER), sizeof(char), 1, archOut) <= 0) return ERROR;
return SUCCESS;
}
//---------------------------------------------------------------------
// READ LETTER
//--------------------------------------------------------------------
int readLetter(FILE* arch, long pos, char* letter) {
if (fseek(arch, pos, SEEK_SET) == ERROR) return ERROR;
if (fread(letter, sizeof(char), 1, arch) <= 0) return ERROR;
return SUCCESS;
}
//--------------------------------------------------------------------
// CAPICUA
//---------------------------------------------------------------------
int capicua(FILE *archIn, long begin, long end, FILE *archOut) {
char letterA, letterB;
bool isCapicua = true;
long size = (end - begin);
long leftPos = begin, rightPos = end-1;
if (size == 0) return SUCCESS;
while (leftPos <= rightPos) {
if (readLetter(archIn, leftPos, &letterA) == ERROR) return ERROR;
if (readLetter(archIn, rightPos, &letterB) == ERROR) return ERROR;
int a = tolower(letterA);
int b = tolower(letterB);
if (a != b) {
isCapicua = false;
break;
}
rightPos--;
leftPos++;
}
if (!isCapicua) return SUCCESS;
if (writeOutFile(archIn, begin, end, archOut) == ERROR) return ERROR;
return SUCCESS;
}
//--------------------------------------------------------------------
// READ FILE
//--------------------------------------------------------------------
int readFile(FILE* archIn, FILE* archOut) {
if (archIn != stdin) {
if (fseek(archIn, 0, SEEK_END) == ERROR) return ERROR;
if (ftell(archIn) == 0) return SUCCESS;
if (fseek(archIn, 0, SEEK_SET) == ERROR) return ERROR;
}
if (archOut != stdout) {
if (fseek(archOut, 0, SEEK_SET) == ERROR) return ERROR;
}
long begin = ftell(archIn);
long end = begin;
long last;
int c = getc(archIn);
bool first = false;
while (c != EOF) {
if (belongsToSpace(c)) {
if (!first) {
first = true;
begin = ftell(archIn) - 1;
}
end = ftell(archIn);
} else {
first = false;
last = ftell(archIn);
if (capicua(archIn, begin, end, archOut) == ERROR) return ERROR;
begin = end;
if (fseek(archIn, last, SEEK_SET) == ERROR) return ERROR;
}
c = getc(archIn);
}
long actualPos = ftell(archIn);
if (fseek(archIn, 0, SEEK_END) == ERROR) return ERROR;
long finalPos = ftell(archIn);
if (actualPos != finalPos) return ERROR;
return SUCCESS;
}
//--------------------------------------------------------------------
// EQUAL
//---------------------------------------------------------------------
bool equal(const char* str1, const char* str2) {
return strcmp(str1, str2) == 0;
}
//--------------------------------------------------------------------
// ARG PARSE
//--------------------------------------------------------------------
int argParse(int argc, char** argv, FILE** descriptors, int* clean_exit) {
int arg = 1;
const int size = 8;
const char* flags[] = {"-i", "-o", "-V", "-h", "--version", "--help",
"--input", "--output"};
bool std;
char* flag = "";
bool isFlagNull;
while (arg < argc) {
isFlagNull = true;
if (argv[arg][0] == '-') {
for (int i = 0; i < size; i++) {
if (strcmp(argv[arg], flags[i]) == 0) {
flag = argv[arg];
isFlagNull = false;
break;
}
}
if (equal(flag, "-h") || equal(flag, "--help")) {
printf("%s\n", help_str);
*clean_exit = 1;
return SUCCESS;
}
if (equal(flag, "-V") || equal(flag, "--version")) {
printf("tp0: version %s\n", VERSION);
*clean_exit = 1;
return SUCCESS;
}
if (isFlagNull) {
printf("Invalid argument: %s\n", argv[arg]);
descriptors[0] = NULL;
return ERROR;
}
} else {
std = equal(argv[arg], "-");
if ((equal(flag, "-i") || equal(flag, "--input")) && !std) {
descriptors[0] = fopen(argv[arg], "r");
if (descriptors[0] == NULL) return ERROR;
} else if ((equal(flag, "-o") || equal(flag, "--output")) && !std) {
descriptors[1] = fopen(argv[arg], "w");
if (descriptors[1] == NULL) return ERROR;
}
flag = "nullStr";
}
arg++;
}
return SUCCESS;
}
//-----------------------------------------------------------------
// STDIN CAPICUA
//-----------------------------------------------------------------
int stdinCapicua(const char* word, size_t len) {
size_t cur = 0;
while (cur < len) {
if (tolower(word[cur]) != tolower(word[len - cur - 1])) {
return false;
}
cur++;
}
return true;
}
//------------------------------------------------------------------
// READ STDIN
//---------------------------------------------------------------------
// Función aparte para stdin, la optimización de memoria de fseek usada
// en el caso anterior no es posible leyendo de stdin
int readStdin(FILE* out) {
size_t word_len = 1024;
char* word = (char*) malloc(sizeof(char) * word_len);
memset(word, 0, word_len);
if (word == NULL) return ERROR;
char c = (char) fgetc(stdin);
size_t cur = 0;
while (c != EOF) {
if (belongsToSpace(c)) {
if (cur >= word_len) {
word_len *= 2;
printf("ACA\n");
word = (char*) realloc(word, word_len);
}
word[cur++] = c;
} else {
if (stdinCapicua(word, cur)) {
if (fprintf(out, "%s\n", word) < 0) {
free(word);
return ERROR;
}
}
memset(word, 0, word_len);
cur = 0;
}
c = (char) fgetc(stdin);
}
free(word);
return SUCCESS;
}
//---------------------------------------------------------------------
// MAIN
//--------------------------------------------------------------------
int main(int argc, char** argv) {
FILE* fdescriptors[2] = {stdin, stdout};
int clean_exit = 0;
if (argParse(argc, argv, fdescriptors, &clean_exit) == ERROR) return 1;
if (clean_exit) return 0; // finalizacion limpia, cuando se usa -h o -V
chargeSpace();
if (fdescriptors[0] == stdin) {
if (readStdin(fdescriptors[1]) == ERROR) return 1;
} else {
if (readFile(fdescriptors[0], fdescriptors[1]) == ERROR) return 1;
if (fclose(fdescriptors[0]) == EOF) return 1;
}
if (fdescriptors[1] != stdout && fclose(fdescriptors[1]) == EOF) return 1;
return 0;
}
//--------------------------------------------------------------------
\end{lstlisting}
\newpage
\section{Anexo B: Código Assembly MIPS}
Este código fue generado compilando el programa en la plataforma MIPS con los siguientes parámetros:
\texttt{gcc -std=c99 -o0 -mrnames}
Los parámetros \texttt{o0} y \texttt{mrnames} hacen que el código producido no tenga optimizaciones algunas, y reemplaza los nombres de los registros numéricos por los nombres convencionales usados en manuales de la arquitectura, respectivamente.
\begin{lstlisting}
.file 1 "tp0.c"
.section .mdebug.abi32
.previous
.abicalls
.globl help_str
.rdata
.align 2
.type help_str, @object
.size help_str, 244
help_str:
.ascii "Usage:\n"
.ascii " tp0 -h\n"
.ascii " tp0 -V\n"
.ascii " tp0 [options]\n"
.ascii "Options:\n"
.ascii " -V, --version\tPrint version and quit.\n"
.ascii " -h, --help\tPrint this information.\n"
.ascii " -i, --input\tLocation of the input file.\n"
.ascii " -o, --output\tLocation of the output file.\n"
.ascii "Examples:\n"
.ascii " tp0 -i ~/input -o\n\000"
.globl ENTER
.type ENTER, @object
.size ENTER, 1
ENTER:
.byte 10
.text
.align 2
.globl chargeSpace
.ent chargeSpace
chargeSpace:
.frame $fp,24,$ra # vars= 8, regs= 2/0, args= 0, extra= 8
.mask 0x50000000,-4
.fmask 0x00000000,0
.set noreorder
.cpload $t9
.set reorder
subu $sp,$sp,24
.cprestore 0
sw $fp,20($sp)
sw $gp,16($sp)
move $fp,$sp
sw $zero,8($fp)
sw $zero,12($fp)
$L18:
lw $v0,12($fp)
slt $v0,$v0,123
bne $v0,$zero,$L21
b $L19
$L21:
lw $v0,12($fp)
sll $v1,$v0,2
la $v0,spaceIndex
addu $v1,$v1,$v0
li $v0,-1 # 0xffffffffffffffff
sw $v0,0($v1)
lw $v0,12($fp)
addu $v0,$v0,1
sw $v0,12($fp)
b $L18
$L19:
li $v0,97 # 0x61
sw $v0,12($fp)
$L22:
lw $v0,12($fp)
slt $v0,$v0,123
bne $v0,$zero,$L25
b $L23
$L25:
lw $v1,8($fp)
la $v0,space
addu $v1,$v1,$v0
lbu $v0,12($fp)
sb $v0,0($v1)
lw $v0,12($fp)
sll $v1,$v0,2
la $v0,spaceIndex
addu $v1,$v1,$v0
lw $v0,8($fp)
sw $v0,0($v1)
lw $v0,8($fp)
addu $v0,$v0,1
sw $v0,8($fp)
lw $v0,12($fp)
addu $v0,$v0,1
sw $v0,12($fp)
b $L22
$L23:
li $v0,65 # 0x41
sw $v0,12($fp)
$L26:
lw $v0,12($fp)
slt $v0,$v0,91
bne $v0,$zero,$L29
b $L27
$L29:
lw $v1,8($fp)
la $v0,space
addu $v1,$v1,$v0
lbu $v0,12($fp)
sb $v0,0($v1)
lw $v0,12($fp)
sll $v1,$v0,2
la $v0,spaceIndex
addu $v1,$v1,$v0
lw $v0,8($fp)
sw $v0,0($v1)
lw $v0,8($fp)
addu $v0,$v0,1
sw $v0,8($fp)
lw $v0,12($fp)
addu $v0,$v0,1
sw $v0,12($fp)
b $L26
$L27:
li $v0,48 # 0x30
sw $v0,12($fp)
$L30:
lw $v0,12($fp)
slt $v0,$v0,58
bne $v0,$zero,$L33
b $L31
$L33:
lw $v1,8($fp)
la $v0,space
addu $v1,$v1,$v0
lbu $v0,12($fp)
sb $v0,0($v1)
lw $v0,12($fp)
sll $v1,$v0,2
la $v0,spaceIndex
addu $v1,$v1,$v0
lw $v0,8($fp)
sw $v0,0($v1)
lw $v0,8($fp)
addu $v0,$v0,1
sw $v0,8($fp)
lw $v0,12($fp)
addu $v0,$v0,1
sw $v0,12($fp)
b $L30
$L31:
lw $v0,8($fp)
addu $v0,$v0,1
sw $v0,8($fp)
lw $v1,8($fp)
la $v0,space
addu $v1,$v1,$v0
li $v0,45 # 0x2d
sb $v0,0($v1)
lw $v0,8($fp)
sw $v0,spaceIndex+180
lw $v0,8($fp)
addu $v0,$v0,1
sw $v0,8($fp)
lw $v1,8($fp)
la $v0,space
addu $v1,$v1,$v0
li $v0,95 # 0x5f
sb $v0,0($v1)
lw $v0,8($fp)
sw $v0,spaceIndex+380
move $sp,$fp
lw $fp,20($sp)
addu $sp,$sp,24
j $ra
.end chargeSpace
.size chargeSpace, .-chargeSpace
.align 2
.globl belongsToSpace
.ent belongsToSpace
belongsToSpace:
.frame $fp,24,$ra # vars= 8, regs= 2/0, args= 0, extra= 8
.mask 0x50000000,-4
.fmask 0x00000000,0
.set noreorder
.cpload $t9
.set reorder
subu $sp,$sp,24
.cprestore 0
sw $fp,20($sp)
sw $gp,16($sp)
move $fp,$sp
sw $a0,24($fp)
lw $v0,24($fp)
slt $v0,$v0,123
bne $v0,$zero,$L35
sw $zero,8($fp)
b $L34
$L35:
lw $v0,24($fp)
sll $v1,$v0,2
la $v0,spaceIndex
addu $v0,$v1,$v0
lw $v1,0($v0)
li $v0,-1 # 0xffffffffffffffff
xor $v0,$v1,$v0
sltu $v0,$zero,$v0
sw $v0,8($fp)
$L34:
lw $v0,8($fp)
move $sp,$fp
lw $fp,20($sp)
addu $sp,$sp,24
j $ra
.end belongsToSpace
.size belongsToSpace, .-belongsToSpace
.align 2
.globl writeOutFile
.ent writeOutFile
writeOutFile:
.frame $fp,56,$ra # vars= 16, regs= 3/0, args= 16, extra= 8
.mask 0xd0000000,-8
.fmask 0x00000000,0
.set noreorder
.cpload $t9
.set reorder
subu $sp,$sp,56
.cprestore 16
sw $ra,48($sp)
sw $fp,44($sp)
sw $gp,40($sp)
move $fp,$sp
sw $a0,56($fp)
sw $a1,60($fp)
sw $a2,64($fp)
sw $a3,68($fp)
lw $a0,56($fp)
lw $a1,60($fp)
move $a2,$zero
la $t9,fseek
jal $ra,$t9
bgez $v0,$L37
li $v0,1 # 0x1
sw $v0,32($fp)
b $L36
$L37:
sw $zero,28($fp)
$L38:
lw $v1,64($fp)
lw $v0,60($fp)
subu $v1,$v1,$v0
lw $v0,28($fp)
slt $v0,$v0,$v1
bne $v0,$zero,$L41
b $L39
$L41:
addu $a0,$fp,24
li $a1,1 # 0x1
li $a2,1 # 0x1
lw $a3,56($fp)
la $t9,fread
jal $ra,$t9
bne $v0,$zero,$L42
li $v0,1 # 0x1
sw $v0,32($fp)
b $L36
$L42:
addu $a0,$fp,24
li $a1,1 # 0x1
li $a2,1 # 0x1
lw $a3,68($fp)
la $t9,fwrite
jal $ra,$t9
bne $v0,$zero,$L40
li $v0,1 # 0x1
sw $v0,32($fp)
b $L36
$L40:
lw $v0,28($fp)
addu $v0,$v0,1
sw $v0,28($fp)
b $L38
$L39:
la $a0,ENTER
li $a1,1 # 0x1
li $a2,1 # 0x1
lw $a3,68($fp)
la $t9,fwrite
jal $ra,$t9
bne $v0,$zero,$L44
li $v0,1 # 0x1
sw $v0,32($fp)
b $L36
$L44:
sw $zero,32($fp)
$L36:
lw $v0,32($fp)
move $sp,$fp
lw $ra,48($sp)
lw $fp,44($sp)
addu $sp,$sp,56
j $ra
.end writeOutFile
.size writeOutFile, .-writeOutFile
.align 2
.globl readLetter
.ent readLetter
readLetter:
.frame $fp,48,$ra # vars= 8, regs= 3/0, args= 16, extra= 8
.mask 0xd0000000,-8
.fmask 0x00000000,0
.set noreorder
.cpload $t9
.set reorder
subu $sp,$sp,48
.cprestore 16
sw $ra,40($sp)
sw $fp,36($sp)
sw $gp,32($sp)
move $fp,$sp
sw $a0,48($fp)
sw $a1,52($fp)
sw $a2,56($fp)
lw $a0,48($fp)
lw $a1,52($fp)
move $a2,$zero
la $t9,fseek
jal $ra,$t9
move $v1,$v0
li $v0,1 # 0x1
bne $v1,$v0,$L46
li $v0,1 # 0x1
sw $v0,24($fp)
b $L45
$L46:
lw $a0,56($fp)
li $a1,1 # 0x1
li $a2,1 # 0x1
lw $a3,48($fp)
la $t9,fread
jal $ra,$t9
bne $v0,$zero,$L47
li $v0,1 # 0x1
sw $v0,24($fp)
b $L45
$L47:
sw $zero,24($fp)
$L45:
lw $v0,24($fp)
move $sp,$fp
lw $ra,40($sp)
lw $fp,36($sp)
addu $sp,$sp,48
j $ra
.end readLetter
.size readLetter, .-readLetter
.align 2