Test Foro de elhacker.net SMF 2.1

Programación => Programación C/C++ => Mensaje iniciado por: cbug en 10 Julio 2010, 23:53 PM

Título: [C] - Problemas con archivos - SOLUCIONADO
Publicado por: cbug 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:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void Lee_Caracter(char *RUTA);
void Lee_Lineas(char *RUTA);
void Menu(void);
char *itoa(int val, int base);

void Limpiar_Buffer(void)
{
 while(getchar() != '\n');
}


int main()
{
 
 int opt;
 char *ruta_local = "texto.txt";
 Menu();
 scanf("%d", &opt);
 Limpiar_Buffer();
 while(opt != 0)
 {
   switch(opt)
   {
     case 1:
     {
Lee_Caracter(ruta_local);
break;
     }
     case 2:
     {
Lee_Lineas(ruta_local);
break;
     }      
     default:
break;
   }
   Menu();
   scanf("%d", &opt);
   Limpiar_Buffer();
 }
 return 0;
}


char* itoa(int val, int base){
 static char buf[32] = {0};
 int i = 30;
 for(; val && i ; --i, val /= base)
   buf[i] = "0123456789abcdef"[val % base];
 return &buf[i+1];
}

void Menu(void)
{
 puts("\t**** MENU ****\t");
 puts("1- Leer caracter a caracter");
 puts("2- Leer linea a linea");
 puts("0- Salir");
 puts("Ingrese Opcion>");
}

void Lee_Caracter(char *RUTA)
{
 FILE *fp;
 char buffer;
 fp = fopen(RUTA, "r");
 if(!fp)
   puts("Error al intentar abrir archivo");
 else
   while((buffer = getc(fp)) != EOF)
     printf("%c", buffer);
 putchar(buffer);
 fclose(fp);
}

void Lee_Lineas(char *RUTA)
{
 FILE *fp;
 char *buffer;
 char *mi_eof = NULL;
 mi_eof = atoi(EOF, 10);
 fp = fopen(RUTA, "r");
 if(!fp)
   puts("Error al intentar abrir archivo");
 else
 {
   buffer = (char *)(malloc(sizeof(char) * 100));
   fgets(buffer, sizeof(char) * 100, fp);
   
   while(strstr(buffer, mi_eof) != NULL);
   {
     puts(buffer);
     free(buffer);
     buffer = (char *)(malloc(sizeof(char) * 100));
     fgets(buffer, sizeof(char) * 100, fp);
   }
 }
 free(buffer);
 fclose(fp);
}


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

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.
Título: Re: [C] - Problemas con archivos
Publicado por: leogtz en 11 Julio 2010, 00:03 AM
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

case ALGO:
/* codigo */
break;


Saludos.
Título: Re: [C] - Problemas con archivos
Publicado por: cbug en 11 Julio 2010, 00:12 AM
void Lee_Lineas(char *RUTA)
{
 FILE *fp;
 char *buffer;
 char *mi_eof = NULL;
 mi_eof = itoa(EOF, 10);
 fp = fopen(RUTA, "r");
 if(!fp)
   puts("Error al intentar abrir archivo");
 else
 {
   buffer = malloc(sizeof(char) * 100);
   fgets(buffer, sizeof(char) * 100, fp);
   
   while(strstr(buffer, mi_eof) == NULL);
   {
     puts(buffer);
     buffer = malloc(sizeof(char) * 100);
     fgets(buffer, sizeof(char) * 100, fp);
   }
 }
 free(buffer);
 fclose(fp);
}


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:

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]

void Lee_Lineas(char *RUTA)
{
  FILE *fp;
  char *buffer;
  fp = fopen(RUTA, "r");
  if(!fp)
    puts("Error al intentar abrir archivo");
  else
  {
    buffer = malloc(sizeof(char) * 100);
   
    while(fgets(buffer, sizeof(char) * 100, fp));
    {
      puts(buffer);
      buffer = malloc(sizeof(char) * 100);
    }
  }
  free(buffer);
  fclose(fp);
}
Título: Re: [C] - Problemas con archivos
Publicado por: leogtz 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:

void Lee_Lineas(char *ruta)
{
 FILE *archivo = fopen(ruta, "r");
 if(archivo == NULL)
 {
     perror("Problema abriendo archivo.");
 } else {
     char linea[500];
     while(fgets(linea, 500, archivo) != NULL)
         printf("%s", linea);
 }
   fclose(archivo);
}
Título: Re: [C] - Problemas con archivos
Publicado por: cbug en 11 Julio 2010, 00:19 AM
Cierto, justo había leído el man. Solucionado :)
Título: Re: [C] - Problemas con archivos - SOLUCIONADO
Publicado por: leogtz 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:

char vector[LIM]

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

saludos.
Título: Re: [C] - Problemas con archivos - SOLUCIONADO
Publicado por: cbug 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()