~eaglescreen/ple/2010-2011

« back to all changes in this revision

Viewing changes to BELMONTE RAFAEL 3ra EVALUACION/Ficheros Binarios/00a_grabar_ficheros.c

  • Committer: Rafael Belmonte
  • Date: 2011-03-27 13:37:36 UTC
  • Revision ID: eaglescreen@gmail.com-20110327133736-3ooxj7qs93rl5779
Ficheros; atou, MiStricmp; uconio.c:cgets mejorada

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
/*******************************************************
 
2
Programa para familiarizarse con las funciones para
 
3
trabajar con ficheros binarios
 
4
*******************************************************/
 
5
#include <stdio.h>
 
6
#include <stdlib.h>
 
7
#include <string.h>
 
8
# include <termios.h>
 
9
# include <unistd.h>
 
10
 
 
11
#define OK 0
 
12
#define ERR !OK
 
13
 
 
14
typedef struct persona
 
15
{
 
16
        unsigned edad;
 
17
        char nombre[50];
 
18
        char sexo[6];
 
19
} PERSONA;
 
20
 
 
21
void clrscr(void);
 
22
char getch(void);
 
23
char * cgets(char *str);
 
24
unsigned atou(char *str);
 
25
 
 
26
int main()
 
27
{
 
28
        FILE *fbin;
 
29
        PERSONA socio;
 
30
        char aux[53];
 
31
        
 
32
        printf("\nRellene los siguientes campos: ");
 
33
        printf("\n\nEdad: ");
 
34
        aux[0]=3;
 
35
        socio.edad=atou(cgets(aux));
 
36
        printf("\n\nNombre: ");
 
37
        aux[0]=50;
 
38
        strcpy(socio.nombre,cgets(aux));
 
39
        printf("\n\nSexo: ");
 
40
        aux[0]=6;
 
41
        strcpy(socio.sexo,cgets(aux));
 
42
        printf("\n\nGracias, pulse una tecla para continuar...");
 
43
        getch();
 
44
        fbin=fopen("personas.dat","ab");
 
45
        if (!fbin) exit(ERR);
 
46
        fwrite(&socio, sizeof(PERSONA), 1, fbin);
 
47
        fclose(fbin);
 
48
        return OK;
 
49
}
 
50
 
 
51
/*=========================================================================================================================================*/
 
52
 
 
53
unsigned atou(char *str)
 
54
{
 
55
        unsigned Pow(unsigned base, unsigned exp)
 
56
        {
 
57
                unsigned i;
 
58
                unsigned ret=1;
 
59
                for(i=0;i<exp;i++)
 
60
                        ret=ret*base;
 
61
                return ret;     
 
62
        }
 
63
        unsigned i, len, end, pos, result;
 
64
        i=len=result=end=0;
 
65
        while(str[len])
 
66
                len++;
 
67
        if (str[0]=='-' || str[0]=='+') end=1;
 
68
        pos=len-1;
 
69
        while((pos>=end) && (pos<=len))
 
70
        {
 
71
                
 
72
                if ((str[pos]>='0') && (str[pos]<='9'))
 
73
                {
 
74
                        result+=(unsigned)((str[pos--]-'0')*(Pow(10,i)));
 
75
                        i++;
 
76
                }
 
77
                else /*if (str[pos]=='.')*/
 
78
                {
 
79
                        result=i=0;
 
80
                        pos--;
 
81
                }       
 
82
        }
 
83
        return result;
 
84
}
 
85
 
 
86
/********************************************
 
87
Funcion: getch
 
88
Descripcion:
 
89
        Recoge un caracter de la entrada estándar
 
90
        sin echo y sin buffer.
 
91
Retorno:
 
92
        Devuelve el char del caracter leido.
 
93
Dependencias:
 
94
        <termios.h>, <unistd.h>
 
95
********************************************/
 
96
char getch(void) 
 
97
 
98
        char buf = 0; 
 
99
        struct termios old = {0}; 
 
100
        if (tcgetattr(0, &old) < 0) 
 
101
                perror("tcsetattr()"); 
 
102
        old.c_lflag &= ~ICANON; 
 
103
        old.c_lflag &= ~ECHO; 
 
104
        old.c_cc[VMIN] = 1; 
 
105
        old.c_cc[VTIME] = 0; 
 
106
        if (tcsetattr(0, TCSANOW, &old) < 0) 
 
107
                perror("tcsetattr ICANON"); 
 
108
        if (read(0, &buf, 1) < 0) 
 
109
                perror ("read()");
 
110
        old.c_lflag |= ICANON; 
 
111
        old.c_lflag |= ECHO; 
 
112
        if (tcsetattr(0, TCSADRAIN, &old) < 0) 
 
113
                perror ("tcsetattr ~ICANON"); 
 
114
        return (buf); 
 
115
}
 
116
 
 
117
/*******************************************************************************
 
118
Funcion: cgets          Autor: Rafael Belmonte          Fecha: enero de 2011
 
119
 
 
120
Descripción (ES):
 
121
        Lee una cadena.
 
122
        racgets lee una cadena de caracteres desde la consola, guardando la cadena
 
123
    (y la longitud de la cadena) en la dirección de memoria a la que apunta str.
 
124
    racgets lee caracteres hasta que encuentra un carácter de salto de línea \n
 
125
    o hasta que han sido leidos el máximo número de caracteres permitido.
 
126
    Si racgets lee un salto de línea, lo reemplaza por un caracter nulo o fin
 
127
    de cadena \0 antes de guardar la cadena.
 
128
 
 
129
    Antes de llamar a racgets, guarde en str[0] la máxima longitud de la cadena
 
130
    que va a ser leida.
 
131
    A la salida de la función, en str[1] queda guardado el número de caracteres
 
132
    que han sido leídos.
 
133
    Los caracteres leidos comienzan en posición str[2] y terminan con un nulo.
 
134
    Por lo que str debe tener al menos una longitud de str[0] + 3 bytes.
 
135
 
 
136
Argumentos:
 
137
        La función recibe un puntero a char, que apunta al comienzo de una cadena
 
138
    de caracteres.
 
139
 
 
140
Retorno:
 
141
        La función devuelve un puntero que apunta a str[2], ya que es en la posición
 
142
        2 donde comienzan los caracteres leidos.
 
143
*******************************************************************************/
 
144
 
 
145
/***PROTOTIPOS LOCALES***/
 
146
        /*unsigned PilaExt(PILA *);
 
147
        void PilaFree(PILA *);
 
148
        short PilaIns(PILA *, unsigned);
 
149
        short PilaIni(PILA *, unsigned);
 
150
        void borrar(void);
 
151
        short PilaVacia(PILA)*/
 
152
/****************/
 
153
char * cgets(char *str)
 
154
{
 
155
        /***DEFINIR TIPOS***/
 
156
        typedef struct
 
157
        {
 
158
                unsigned top;
 
159
                unsigned *dato;
 
160
                unsigned max;
 
161
        } PILA;
 
162
    /*******************/
 
163
        /***FUNCIONES LOCALES*******/
 
164
        void borrar(void)
 
165
     {
 
166
         putc(8,stdout); /*Si se presiona borrar, se borra*/
 
167
         putc(' ',stdout);
 
168
         putc(8,stdout);
 
169
     }
 
170
     short PilaIni(PILA * pilita, unsigned tam)
 
171
     {
 
172
        pilita->top=0;
 
173
        pilita->max=tam;
 
174
        pilita->dato=(unsigned *)malloc(tam*sizeof(unsigned));
 
175
        if (pilita->dato) return 0;
 
176
        else return 1;
 
177
     }
 
178
     
 
179
     short PilaVacia(PILA pilita)
 
180
     {
 
181
        if (pilita.top==0)
 
182
                return 1;
 
183
        return 0;
 
184
     }
 
185
     
 
186
     short Push(PILA * pilita, unsigned item)
 
187
     {
 
188
        if (pilita->top<pilita->max)
 
189
        {
 
190
                pilita->dato[pilita->top++]=item;
 
191
                return 0;
 
192
        }
 
193
        return 1;
 
194
     }
 
195
     void PilaFree(PILA * pilita)
 
196
     {
 
197
        if (pilita->dato)
 
198
                free(pilita->dato);
 
199
     }
 
200
     unsigned Pop(PILA * pilita)
 
201
     {
 
202
        if (pilita->top)
 
203
                return pilita->dato[--pilita->top];
 
204
        return pilita->dato[pilita->top];
 
205
     }
 
206
        /***************************/
 
207
         PILA tamagnos;/*tamagno del ultimo caracter guardado*/
 
208
     unsigned long i, max;
 
209
     char ch=0;
 
210
     setvbuf(stdout, (char *) NULL, _IONBF, 0);
 
211
     i=2;
 
212
     max=(int)str[0];
 
213
         if (PilaIni(&tamagnos,max)) return NULL;/*PilaIni devuelve x!=0 si hay error*/
 
214
     while ((ch=getch())!='\n')
 
215
     {
 
216
        if(i<max+2) /*¿podemog coger caracteres?*/
 
217
        {
 
218
                if (ch >= 32 && ch <= 126) /*caracteres alfanumericos e imprimibles "normales"*/
 
219
                {
 
220
                        str[i++]=ch;
 
221
                        putchar(ch);
 
222
                        Push(&tamagnos,1);
 
223
                }
 
224
                else if ((ch == -61)&&(max+2-i>=2)) /*vovales con acento o dieresis (2 bytes)*/
 
225
                {
 
226
                        str[i++]=ch;
 
227
                        putchar(ch);
 
228
                        str[i++]=ch=getch();
 
229
                        putchar(ch);
 
230
                        Push(&tamagnos,2);
 
231
                }
 
232
        }
 
233
        if(ch==127)/*borrar*/
 
234
        {
 
235
                if(!PilaVacia(tamagnos))
 
236
                {
 
237
                        borrar();
 
238
                        i=i-Pop(&tamagnos);
 
239
                }
 
240
        }
 
241
     }
 
242
     if (!ch) while(getch()!='\n'); /*Si no se lee nada, se espera a un Enter*/
 
243
     str[i]='\0';
 
244
         i=i-2;
 
245
     str[1]=(char)i;
 
246
     setvbuf(stdout, (char *) NULL, _IOLBF, 0);
 
247
     return &str[2];
 
248
}
 
249
 
 
250
        /***FIN DE CGETS***/