elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: Introducción a la Factorización De Semiprimos (RSA)


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación C/C++ (Moderadores: Eternal Idol, Littlehorse, K-YreX)
| | |-+  [C] - Problemas con archivos - SOLUCIONADO
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: [C] - Problemas con archivos - SOLUCIONADO  (Leído 3,639 veces)
cbug

Desconectado Desconectado

Mensajes: 147



Ver Perfil
[C] - Problemas con archivos - SOLUCIONADO
« en: 10 Julio 2010, 23:53 pm »

Hola, resulta que estaba practicando algo con archivos, y se me ocurrió hacer 2 procedimientos para leer línea a línea y char a char... En fin, este es el code:

Código
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5. void Lee_Caracter(char *RUTA);
  6. void Lee_Lineas(char *RUTA);
  7. void Menu(void);
  8. char *itoa(int val, int base);
  9.  
  10. void Limpiar_Buffer(void)
  11. {
  12.  while(getchar() != '\n');
  13. }
  14.  
  15.  
  16. int main()
  17. {
  18.  
  19.  int opt;
  20.  char *ruta_local = "texto.txt";
  21.  Menu();
  22.  scanf("%d", &opt);
  23.  Limpiar_Buffer();
  24.  while(opt != 0)
  25.  {
  26.    switch(opt)
  27.    {
  28.      case 1:
  29.      {
  30. Lee_Caracter(ruta_local);
  31. break;
  32.      }
  33.      case 2:
  34.      {
  35. Lee_Lineas(ruta_local);
  36. break;
  37.      }      
  38.      default:
  39. break;
  40.    }
  41.    Menu();
  42.    scanf("%d", &opt);
  43.    Limpiar_Buffer();
  44.  }
  45.  return 0;
  46. }
  47.  
  48.  
  49. char* itoa(int val, int base){
  50.  static char buf[32] = {0};
  51.  int i = 30;
  52.  for(; val && i ; --i, val /= base)
  53.    buf[i] = "0123456789abcdef"[val % base];
  54.  return &buf[i+1];
  55. }
  56.  
  57. void Menu(void)
  58. {
  59.  puts("\t**** MENU ****\t");
  60.  puts("1- Leer caracter a caracter");
  61.  puts("2- Leer linea a linea");
  62.  puts("0- Salir");
  63.  puts("Ingrese Opcion>");
  64. }
  65.  
  66. void Lee_Caracter(char *RUTA)
  67. {
  68.  FILE *fp;
  69.  char buffer;
  70.  fp = fopen(RUTA, "r");
  71.  if(!fp)
  72.    puts("Error al intentar abrir archivo");
  73.  else
  74.    while((buffer = getc(fp)) != EOF)
  75.      printf("%c", buffer);
  76.  putchar(buffer);
  77.  fclose(fp);
  78. }
  79.  
  80. void Lee_Lineas(char *RUTA)
  81. {
  82.  FILE *fp;
  83.  char *buffer;
  84.  char *mi_eof = NULL;
  85.  mi_eof = atoi(EOF, 10);
  86.  fp = fopen(RUTA, "r");
  87.  if(!fp)
  88.    puts("Error al intentar abrir archivo");
  89.  else
  90.  {
  91.    buffer = (char *)(malloc(sizeof(char) * 100));
  92.    fgets(buffer, sizeof(char) * 100, fp);
  93.  
  94.    while(strstr(buffer, mi_eof) != NULL);
  95.    {
  96.      puts(buffer);
  97.      free(buffer);
  98.      buffer = (char *)(malloc(sizeof(char) * 100));
  99.      fgets(buffer, sizeof(char) * 100, fp);
  100.    }
  101.  }
  102.  free(buffer);
  103.  fclose(fp);
  104. }

El problema está en mi función atoi, al compilar:

Código:
lectura.c: In function 'Lee_Lineas':
lectura.c:89: warning: passing argument 1 of 'atoi' makes pointer from integer without a cast
lectura.c:89: error: too many arguments to function 'atoi'
lectura.c:89: warning: assignment makes pointer from integer without a cast

No puedo resolverlo.

Ahora bien, tengo una duda más, está bien la forma en que busco el EOF del archivo, en la función Lee_Lineas()?


EDITADO: La primera duda resuelta, estaba dormido y cambié itoa por atoi  :-X
Ahora el problema es que la función Lee_Lineas no funciona  :xD

CORREGIDO: while(strstr(buffer, mi_eof) == NULL)

Creo que el problema está en que no incremento el puntero para leer el archivo.


« Última modificación: 11 Julio 2010, 00:19 am por cbug » En línea

leogtz
. . .. ... ..... ........ ............. .....................
Colaborador
***
Desconectado Desconectado

Mensajes: 3.069


/^$/


Ver Perfil WWW
Re: [C] - Problemas con archivos
« Respuesta #1 en: 11 Julio 2010, 00:03 am »

Código:
int atoi ( const char * str );
No concuerda con tu llamada, estás enviando EOF una macro o un indicador.
Sin contar que la función solo trabaja con un argumento.

malloc() no necesita un casting.

Y para cada clausula dentro del switch(), no son necesarias las llaves

Código:
case ALGO:
/* codigo */
break;

Saludos.


« Última modificación: 11 Julio 2010, 00:09 am por Leo Gutiérrez. » En línea

Código
  1. (( 1 / 0 )) &> /dev/null || {
  2. echo -e "stderrrrrrrrrrrrrrrrrrr";
  3. }
  4.  
http://leonardogtzr.wordpress.com/
leogutierrezramirez@gmail.com
cbug

Desconectado Desconectado

Mensajes: 147



Ver Perfil
Re: [C] - Problemas con archivos
« Respuesta #2 en: 11 Julio 2010, 00:12 am »

Código
  1. void Lee_Lineas(char *RUTA)
  2. {
  3.  FILE *fp;
  4.  char *buffer;
  5.  char *mi_eof = NULL;
  6.  mi_eof = itoa(EOF, 10);
  7.  fp = fopen(RUTA, "r");
  8.  if(!fp)
  9.    puts("Error al intentar abrir archivo");
  10.  else
  11.  {
  12.    buffer = malloc(sizeof(char) * 100);
  13.    fgets(buffer, sizeof(char) * 100, fp);
  14.  
  15.    while(strstr(buffer, mi_eof) == NULL);
  16.    {
  17.      puts(buffer);
  18.      buffer = malloc(sizeof(char) * 100);
  19.      fgets(buffer, sizeof(char) * 100, fp);
  20.    }
  21.  }
  22.  free(buffer);
  23.  fclose(fp);
  24. }

Aqui tengo el problema en que sólo lee la primera línea y sale.

SOLCUCIONADO:

No se necesita comparar, o buscar el EOF, leyendo el man de fgets:

Código:
 Upon successful completion, fgets() and gets() return a pointer to the
     string.  If end-of-file occurs before any characters are read, they
     return NULL and the buffer contents remain unchanged.  If an error
     occurs, they return NULL and the buffer contents are indeterminate.  The
     fgets() and gets() functions do not distinguish between end-of-file and
     error, and callers must use feof(3) and ferror(3) to determine which
     occurred.
[/b]

Código
  1. void Lee_Lineas(char *RUTA)
  2. {
  3.  FILE *fp;
  4.  char *buffer;
  5.  fp = fopen(RUTA, "r");
  6.  if(!fp)
  7.    puts("Error al intentar abrir archivo");
  8.  else
  9.  {
  10.    buffer = malloc(sizeof(char) * 100);
  11.  
  12.    while(fgets(buffer, sizeof(char) * 100, fp));
  13.    {
  14.      puts(buffer);
  15.      buffer = malloc(sizeof(char) * 100);
  16.    }
  17.  }
  18.  free(buffer);
  19.  fclose(fp);
  20. }
« Última modificación: 11 Julio 2010, 00:18 am por cbug » En línea

leogtz
. . .. ... ..... ........ ............. .....................
Colaborador
***
Desconectado Desconectado

Mensajes: 3.069


/^$/


Ver Perfil WWW
Re: [C] - Problemas con archivos
« Respuesta #3 en: 11 Julio 2010, 00:18 am »

Es que no entiendo por qué usar itoa() y strstr() si tu objetivo solo es leer el archivo línea línea.

Yo hice algo así y funciona:

Código
  1. void Lee_Lineas(char *ruta)
  2. {
  3.  FILE *archivo = fopen(ruta, "r");
  4.  if(archivo == NULL)
  5.  {
  6.      perror("Problema abriendo archivo.");
  7.  } else {
  8.      char linea[500];
  9.      while(fgets(linea, 500, archivo) != NULL)
  10.          printf("%s", linea);
  11.  }
  12.   fclose(archivo);
  13. }
  14.  
« Última modificación: 11 Julio 2010, 02:05 am por Leo Gutiérrez. » En línea

Código
  1. (( 1 / 0 )) &> /dev/null || {
  2. echo -e "stderrrrrrrrrrrrrrrrrrr";
  3. }
  4.  
http://leonardogtzr.wordpress.com/
leogutierrezramirez@gmail.com
cbug

Desconectado Desconectado

Mensajes: 147



Ver Perfil
Re: [C] - Problemas con archivos
« Respuesta #4 en: 11 Julio 2010, 00:19 am »

Cierto, justo había leído el man. Solucionado :)
En línea

leogtz
. . .. ... ..... ........ ............. .....................
Colaborador
***
Desconectado Desconectado

Mensajes: 3.069


/^$/


Ver Perfil WWW
Re: [C] - Problemas con archivos - SOLUCIONADO
« Respuesta #5 en: 11 Julio 2010, 00:24 am »

No utilices un array dinámico, puesto que el valor por defecto es 100, así que puedes crearlo directamente:

Código:
char vector[LIM]

Así te evitas el uso de malloc(), free() y la inclusión de stdlib.h.

saludos.
En línea

Código
  1. (( 1 / 0 )) &> /dev/null || {
  2. echo -e "stderrrrrrrrrrrrrrrrrrr";
  3. }
  4.  
http://leonardogtzr.wordpress.com/
leogutierrezramirez@gmail.com
cbug

Desconectado Desconectado

Mensajes: 147



Ver Perfil
Re: [C] - Problemas con archivos - SOLUCIONADO
« Respuesta #6 en: 11 Julio 2010, 00:28 am »

Es que ahora pienso modificarlo, puesto que como dijiste, sólo lee 100 caracteres, y muchas veces el .txt posee más en una sóla línea, y necesitaré prontamente un realloc()
En línea

Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

Mensajes similares
Asunto Iniciado por Respuestas Vistas Último mensaje
[solucionado]problemas con mid vb.net
.NET (C#, VB.NET, ASP)
CH4ØZ 3 4,653 Último mensaje 1 Febrero 2011, 01:43 am
por CH4ØZ
PROBLEMAS CON FAIL2BAN!!!! <solucionado>
GNU/Linux
xarlyuno 1 3,317 Último mensaje 19 Agosto 2011, 12:07 pm
por xarlyuno
(SOLUCIONADO) Problemas con DIV
PHP
dimitrix 0 1,626 Último mensaje 5 Abril 2012, 16:57 pm
por dimitrix
(Solucionado) Importar archivos .PSP de PS CS 5 a PS CS 6
Diseño Gráfico
Eleкtro 0 5,521 Último mensaje 30 Mayo 2012, 15:32 pm
por Eleкtro
Duda archivos en C (solucionado)
Programación C/C++
David8 4 2,786 Último mensaje 19 Mayo 2014, 18:36 pm
por rir3760
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines