| Ver tema anterior :: Ver siguiente tema | | Autor | Mensaje |
|---|
traxcer
Registrado: 19 Ago 2013 Mensajes: 2
| Publicado: 19/08/2013 2:05 am | | | Título: Donde está el error??? |
| He compilado este código que implementa una función para copiar archivos, pero no me funcióna y ya me estoy volviendo loco y no le veo el fallo. A ver si me podeís echar un cable alguno.
Un saludo.
CODIGO::
#include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <string.h>
int copiaf(char *f1, char* f2){ int fd_leer; int fd_escribir; ssize_t leido; ssize_t escrito; char bufi[20];
if(fd_leer = open(f1,O_RDONLY)< 0){ perror ("Error en Lectura:"); exit (-1); } if(fd_escribir = open(f2,O_WRONLY|O_TRUNC|O_CREAT,666) < 0){ perror("Error en Escritura:"); exit (-1); } //////////// // LECTURA y ESCRITURA ////////////
while (leido = read(fd_leer,bufi,sizeof bufi)>0) { printf ("Leidos: %d bytes\n",leido); escrito = write(fd_escribir,bufi,sizeof bufi); } if (leido == 0) { printf("Fin del Fichero"); close(fd_leer); close(fd_escribir); exit (-1); } else if (leido < 0){ perror("Lectura:"); } }
int main(int argc, char **argv) { int resultado; if (argc != 3){ printf ("Usar: %s origen destino\n\n",argv[0]); exit (-1); } if ((resultado= copiaf (argv[1], argv[2]))<0); printf ("Error en la copia"); return 0; } |
| | Volver arriba | |  | rir3760

Registrado: 01 Oct 2004 Mensajes: 7527 Ubicación: Mexico
| Publicado: 19/08/2013 8:33 am | | | Título: |
| Hola
Bienvenido a los foros. Por favor lee sus reglas.
Errores hay varios. Algunos de estos son:
* En la apertura de los archivos te faltan paréntesis. Para que tengan el resultado esperado debes colocarlos de esta forma:
| Código: | if ((fd_leer = open(f1, O_RDONLY)) < 0){ perror("Error en Lectura:"); exit(-1); } if ((fd_escribir = open(f2, O_WRONLY | O_TRUNC | O_CREAT, 666)) < 0){ perror ("Error en Escritura:"); exit (-1); } |
* Otro error en el mismo bloque: no cierras el primer archivo en el caso donde este se abra correctamente pero falle la apertura del segundo. Para ello se debe cambiar el segundo condicional a:
| Código: | if ((fd_leer = open(f1, O_RDONLY)) < 0){ perror("Error en Lectura:"); exit(-1); }
/* fd_leer se abrio correctamente */ if ((fd_escribir = open(f2, O_WRONLY | O_TRUNC | O_CREAT, 666)) < 0){ perror ("Error en Escritura:"); close(fd_leer) exit (-1); } |
* En el bucle principal también faltan paréntesis y siempre escribes "sizeof bufi" caracteres en el archivo de salida cuando deberías utilizar el valor almacenado en "leido". Hay que cambiar el bucle a:
| Código: | while ((leido = read(fd_leer, bufi, sizeof bufi)) > 0) { printf("Leidos: %d bytes\n", leido); escrito = write(fd_escribir, bufi, leido); } |
* Al final de la función y si sucede un error no cierras los archivos, los cambios ahí son similares a los que se requieren en la apertura de los mismos.
* Almacenas un valor en la variable "escrito" pero no lo utilizas, tienes un punto y coma demás en el segundo condicional en la función main.
* Algunos mas ...
El programa con todos los cambios:
| Código: | #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <string.h>
#include <stdlib.h> /* EXIT_SUCCESS y EXIT_FAILURE */
int copiaf (char *f1, char* f2) { int fd_leer; int fd_escribir; ssize_t leido; char bufi[20]; if ((fd_leer = open(f1, O_RDONLY)) < 0){ perror("Error en Lectura:"); exit(EXIT_FAILURE); } if ((fd_escribir = open(f2, O_WRONLY | O_TRUNC | O_CREAT, 666)) < 0){ perror ("Error en Escritura:"); close(fd_leer); exit(EXIT_FAILURE); }
while ((leido = read (fd_leer, bufi, sizeof bufi)) > 0){ printf("Leidos: %d bytes\n", leido); write(fd_escribir, bufi, leido); } close(fd_leer); close(fd_escribir); if (leido < 0){ perror("Error en la lectura del archivo"); exit(EXIT_FAILURE); } return EXIT_SUCCESS; }
int main(int argc, char **argv) { int resultado; if (argc != 3){ printf("Usar: %s origen destino\n\n", argv[0]); return EXIT_FAILURE; } resultado = copiaf (argv[1], argv[2]); if (resultado < 0) perror("Error en la copia"); return EXIT_SUCCESS; } |
Un saludo _________________ C retains the basic philosophy that programmers know what they are doing; it only requires that they state their intentions explicitly. -- Kernighan & Ritchie, The C programming language |
| | Volver arriba | |  | traxcer
Registrado: 19 Ago 2013 Mensajes: 2
| Publicado: 19/08/2013 3:07 pm | | | Título: |
| Antes de nada mucha gracias, ahora si me funciona medio bien, pero aun tengo un problema, el fichero creado tiene en los permisos una T ¿? Y no me deja visualizarlo, adjunto captura de pantalla de la info de directorio y la ejecución del programa:
| Código: |
[alumno@fsc build]$ ./cp_fsc fichero1 test Leidos: 20 bytes Leidos: 20 bytes Leidos: 20 bytes Leidos: 3 bytes Fin del Fichero[alumno@fsc build]$ ls -la total 56 drwxrwxr-x. 3 alumno alumno 4096 Aug 20 01:03 . drwxrwxr-x. 4 alumno alumno 4096 Aug 20 01:02 .. -rw-rw-r--. 1 alumno alumno 10910 Aug 19 09:50 CMakeCache.txt drwxrwxr-x. 6 alumno alumno 4096 Aug 20 01:02 CMakeFiles -rw-rw-r--. 1 alumno alumno 1665 Aug 19 09:50 cmake_install.cmake -rwxrwxr-x. 1 alumno alumno 7623 Aug 20 01:02 cp_fsc -rw-rw-r--. 1 alumno alumno 63 Aug 19 10:05 fichero1 -rw-rw-r--. 1 alumno alumno 4734 Aug 19 09:50 Makefile ]--w--wx--T. 1 alumno alumno 63 Aug 20 01:03 test <---- Fichero Copiado [alumno@fsc build]$
|
|
| | Volver arriba | |  | | rir3760

Registrado: 01 Oct 2004 Mensajes: 7527 Ubicación: Mexico
| Publicado: 20/08/2013 6:34 am | | | Título: |
| Con las modificaciones que te indique la copia se realiza correctamente, eso lo puedes verificar utilizando el comando diff (mas información sobre este mediante "diff --help").
En cuanto al atributo "T" en un sistema Linux no puedo ayudarte (utilizo MS Windows y Cygwin) pero puedes buscar información en la red (por ejemplo what does meen drwxr-xr-T permission?).
Un saludo _________________ C retains the basic philosophy that programmers know what they are doing; it only requires that they state their intentions explicitly. -- Kernighan & Ritchie, The C programming language |
| | Volver arriba | |  | | |
| No puede crear mensajes No puede responder temas No puede editar sus mensajes No puede borrar sus mensajes No puede votar en encuestas
|
|
| |