Ver Mensaje Individual
  #1 (permalink)  
Antiguo 09/05/2012, 10:00
DickGumshoe
 
Fecha de Ingreso: enero-2012
Mensajes: 68
Antigüedad: 12 años, 3 meses
Puntos: 0
Pequeño error en ficheros

Hola.

Estoy intentando leer las n últimas líneas de un fichero, para, posteriormente, almacenarlas en otro.

Por ejemplo, si mi fichero tiene:

Código:
hola
adiós
duda
ficheros
punteros
estructuras
y meto el número 3 por consola, después de introducir el nombre del fichero, me debería leer:

Cita:
ficheros
punteros
estructuras
Y, sin embargo, me lee:

Código:
os
punteros
estructuras
Mi código es:

Código C:
Ver original
  1. #include<stdio.h>
  2. #include<stdlib.h>
  3.  
  4. typedef struct{
  5.  
  6. int *V;
  7. int lineas;
  8.  
  9. }Estructura;
  10.  
  11. char* InicializarCadena();
  12. Estructura Contar(FILE *fp);
  13. void Almacenar(FILE *fp1,FILE *fp2,Estructura aux,int n);
  14.  
  15. int main (){
  16.  
  17. FILE *fp1;
  18. FILE *fp2;
  19.  
  20. int n;
  21.  
  22. char *fich,c;
  23.  
  24. Estructura aux;
  25.  
  26. printf("Introduzca el nombre del fichero: ");
  27.  
  28. fich=InicializarCadena();
  29.  
  30.  
  31. printf("Introduce un numero: ");
  32. scanf("%d", &n);
  33.  
  34.  * *fp1=fopen(fich, "r");
  35.  * *fp2=fopen("Trabajo.txt", "w");
  36.  
  37.  
  38.  * *if(fp1==NULL){
  39.  * *printf("ERROR");
  40.  * *system("pause");
  41.  * *exit(1);
  42.  * *}
  43.  
  44.  * *aux=Contar(fp1);
  45.  
  46.  
  47.  * *Almacenar(fp1,fp2,aux,n);
  48.  
  49.  free(aux.V);
  50.  free(fich);
  51.  fclose(fp1);
  52.  fclose(fp2);
  53.  
  54. system("pause");
  55. }
  56.  
  57.  
  58. char* InicializarCadena(){
  59.  * int i = 0;
  60.  * char c, *cad;
  61.  
  62.  * cad = (char*) malloc(sizeof(char));
  63.  
  64.  * while((c = getchar())!= '\n'){
  65.  * * *cad[i] = c;
  66.  * * *i++;
  67.  * * *cad = (char*)realloc(cad, (i + 1)*sizeof(char));
  68.  * }
  69.  * cad[i] = '\0';
  70.  
  71.  * return cad;
  72. }
  73.  
  74. Estructura Contar(FILE *fp){
  75.  
  76. int i=0;
  77.  
  78. Estructura aux;
  79.  
  80. char c;
  81.  
  82. aux.lineas=0;
  83.  
  84. aux.V=(int*) malloc(sizeof(int));
  85.  
  86. while(feof(fp)==0){
  87.  
  88. c=fgetc(fp);
  89. i++;
  90.  
  91. if(c=='\n'){
  92. aux.V=(int*) realloc(aux.V,(aux.lineas+1)*sizeof(int));
  93. aux.V[aux.lineas]=i;
  94.  
  95. aux.lineas++;
  96. }
  97. }
  98. aux.lineas++;
  99. return(aux);
  100. }
  101.  
  102. void Almacenar(FILE *fp1,FILE *fp2,Estructura aux,int n){
  103.  
  104. char c;
  105.  
  106. fseek(fp1,aux.V[aux.lineas-n],SEEK_SET);
  107.  
  108.  
  109.  
  110. while(feof(fp1)==0){
  111.  
  112. c = fgetc(fp1);
  113. fputc(c,fp2);
  114. printf("%c", c);
  115.  
  116. }
  117.  
  118. }


¿Qué hago mal?

Muchas gracias.

Saludos.