Foros del Web » Programación para mayores de 30 ;) » C/C++ »

función para leer archivos binarios

Estas en el tema de función para leer archivos binarios en el foro de C/C++ en Foros del Web. hola. lo que tengo que hacer es ir leyendo los bytes de un archivo (de uno en uno, de dos en dos,etc. dependiendo del valor ...
  #1 (permalink)  
Antiguo 22/10/2010, 07:51
boli-sp
Invitado
 
Mensajes: n/a
Puntos:
función para leer archivos binarios

hola.

lo que tengo que hacer es ir leyendo los bytes de un archivo (de uno en uno, de dos en dos,etc. dependiendo del valor de "n"). este archivo puede ser cualquier tipo de archivo (binario o de texto). la función fgets me valdría para arhivos binarios y de texto?

caracter es una cadena de caracteres del tamaño que necesite (según los bytes que quiera leer). si vamos a leer los bytes de dos en dos, en caracter tendremos los dos bytes leídos. caracter se va a ir sobreescribiendo ya que es una variable temporal.

Código C:
Ver original
  1. while(fgets(caracter,(n+1),fichero)!=NULL)
  2. {
  3. /* código */
  4. }

lo que va a hacer mi programa es ver si hay bytes o bloques de bytes idénticos en el archivo, así que no me interesa mostrar nada por pantalla de lo que vamos a leer.

gracias a las respuestas :D

Última edición por boli-sp; 22/10/2010 a las 10:39
  #2 (permalink)  
Antiguo 23/10/2010, 09:25
 
Fecha de Ingreso: octubre-2010
Ubicación: Edo. de México
Mensajes: 94
Antigüedad: 13 años, 6 meses
Puntos: 9
Respuesta: función para leer archivos binarios

Busca las siguientes funciones.
open()
read()

Estas son llamadas al sistemas asi que tienes que buscarlas en la pagina 3 del man, suerte
  #3 (permalink)  
Antiguo 23/10/2010, 15:36
boli-sp
Invitado
 
Mensajes: n/a
Puntos:
Respuesta: función para leer archivos binarios

gracias por tu respuesta, aunque no me ha sacado de dudas.

planteándolo de otra forma, mi pregunta es: como tengo que hacer para leer un archivo y manejarlo byte a byte? y como se maneja un archivo byte a byte? si estamos hablando de archivos binarios como puede ser un archivo de música o una foto
  #4 (permalink)  
Antiguo 23/10/2010, 16:48
 
Fecha de Ingreso: abril-2010
Ubicación: Rosario
Mensajes: 1.850
Antigüedad: 14 años
Puntos: 228
Respuesta: función para leer archivos binarios

te recomiendo usar la funcion fread. Aqui tienes una buena explicacion: http://www.cplusplus.com/reference/c.../cstdio/fread/

Guardas los bytes en un array que tu defines. y luegos lo manejas como tu quieras.

Código C++:
Ver original
  1. char buffer[n];
  2. fread (buffer,1,n,pFile);
  3. // los n bytes leidos fueron almacenados en buffer
  #5 (permalink)  
Antiguo 23/10/2010, 17:37
 
Fecha de Ingreso: octubre-2010
Ubicación: Edo. de México
Mensajes: 94
Antigüedad: 13 años, 6 meses
Puntos: 9
Respuesta: función para leer archivos binarios

oops mas bien se tiene que buscar en la pagina 2 del man, pero bueno mira.

Código:
OPEN(2)                                                         Linux Programmer's Manual                                                         OPEN(2)

NAME
       open, creat - open and possibly create a file or device

SYNOPSIS
       #include <sys/types.h>
       #include <sys/stat.h>
       #include <fcntl.h>

       int open(const char *pathname, int flags);
       int open(const char *pathname, int flags, mode_t mode);

       int creat(const char *pathname, mode_t mode);

DESCRIPTION
       Given  a  pathname  for  a  file,  open()  returns  a  file descriptor, a small, non-negative integer for use in subsequent system calls (read(2),
       write(2), lseek(2), fcntl(2), etc.).  The file descriptor returned by a successful call will be the lowest-numbered file descriptor not  currently
       open for the process.

       By  default, the new file descriptor is set to remain open across an execve(2) (i.e., the FD_CLOEXEC file descriptor flag described in fcntl(2) is
       initially disabled; the Linux-specific O_CLOEXEC flag, described below, can be used to change this default).  The file offset is set to the begin‐
       ning of the file (see lseek(2)).

       A call to open() creates a new open file description, an entry in the system-wide table of open files.  This entry records the file offset and the
       file status flags (modifiable via the fcntl(2) F_SETFL operation).  A file descriptor is a reference to one of these entries;  this  reference  is
       unaffected  if  pathname  is subsequently removed or modified to refer to a different file.  The new open file description is initially not shared
       with any other process, but sharing may arise via fork(2).

       The argument flags must include one of the following access modes: O_RDONLY, O_WRONLY, or O_RDWR.   These  request  opening  the  file  read-only,
       write-only, or read/write, respectively.

       In  addition,  zero  or more file creation flags and file status flags can be bitwise-or'd in flags.  The file creation flags are O_CREAT, O_EXCL,
       O_NOCTTY, and O_TRUNC.  The file status flags are all of the remaining flags listed below.  The distinction between these two groups of  flags  is
       that  the  file  status  flags can be retrieved and (in some cases) modified using fcntl(2).  The full list of file creation flags and file status
       flags is as follows:

RETURN VALUE
       open() and creat() return the new file descriptor, or -1 if an error occurred (in which case, errno is set appropriately).
Código:
READ(2)                    Linux Programmer's Manual                   READ(2)

NAME
       read - read from a file descriptor

SYNOPSIS
       #include <unistd.h>

       ssize_t read(int fd, void *buf, size_t count);

DESCRIPTION
       read()  attempts to read up to count bytes from file descriptor fd into
       the buffer starting at buf.

       If count is zero, read() returns zero and has  no  other  results.   If
       count is greater than SSIZE_MAX, the result is unspecified.

RETURN VALUE
       On success, the number of bytes read is returned (zero indicates end of
       file), and the file position is advanced by this number.  It is not  an
       error  if  this  number  is smaller than the number of bytes requested;
       this may happen for example because fewer bytes are actually  available
       right  now  (maybe  because we were close to end-of-file, or because we
       are reading from a pipe, or from a terminal),  or  because  read()  was
       interrupted  by  a  signal.  On error, -1 is returned, and errno is set
       appropriately.  In this case it is left unspecified  whether  the  file
       position (if any) changes.

veras que con estas dos funciones puedes leer cualquier tipo de archivo byte a byte. Solo no quieras que te den todo en bandeja de plata, hay que leer de vez en cuando ^^

Saludos++

Etiquetas: binario
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 22:34.