SoloCodigo

Programación General => C/C++ => Mensaje iniciado por: amedinadiaz en Miércoles 25 de Febrero de 2004, 17:49

Título: Imprimir En Tu Prog. El Contenido De Un Fichero
Publicado por: amedinadiaz en Miércoles 25 de Febrero de 2004, 17:49
Alguno podria decirme como imprimir el conteido de un fichero (FILE *loquesea) en la pantalla de tu programa??

Por ejemplo, si tuviera escrito en un txt una algo asi:

1
2
3
4
5
6
7
8
9
10

Como ariais para que saliesen el contenido de este txt en vuestra pantalla? (sin crear otro fichero)

Y aun mas dificil (al menos para mi:P ejeje) como ariais para imprimir una serie de caracteres? Por ejemplo.

Hola me llamo Pedro.
Esto es una tonteria.
Tengo que esxcrbir algo.

Gracias x vuestro tiempo y si lo descubro ya lo pondre aqui!
Título: Re: Imprimir En Tu Prog. El Contenido De Un Fichero
Publicado por: nicokiki en Miércoles 25 de Febrero de 2004, 19:46
Para imprimir por pantalla una linea es facil:

#include <iostream.h>
#include <stdio.h>

void main(void)
{
   cout<<"Hola me llamo Pedro"<<endl;
}

Y listo.

Ahora para imprimir algo por pantalla leido de un archivo sigue siendo al muy facil de hacer pero es mas largo y hay q validar ciertas cosas

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

void main(void)
{
   CString Linea;
   CString Nombre = "c:\\archivo.txt";
   FILE* Archivo=fopen(NombreArchivo, "r");
   
   //Ojo q lo q viene no lo probe y no se q cambio habria q hacer
   while (!feof(Archivo))
   {
      //Llama a una funcion q parsee el archivo, q lo q deberia hacer es por ejemplo
      //un fgets(LineaAux, LongitudDeLinea, Archivo) q devuelve un puntero a char
      Linea = ParsearUnaLineaDeArchivo(Archivo);
      Limpiarlinea();
      cout<<Linea<<endl;
   }
   
}

Salu2!!!!! y recorda q esto no si anda, mas bien quise escribir un poco de codigo de como seria la cosa en general
Título: Re: Imprimir En Tu Prog. El Contenido De Un Fichero
Publicado por: carmamezo en Viernes 27 de Febrero de 2004, 14:26
Bueno... aki te mando un ejemplo en C:
Código: Text
  1.  
  2. Void main()
  3. {
  4. FILE *pf;
  5. int a;
  6.  
  7. if((pf=fopen(&#34;archivo&#34;,&#34;r&#34;))==NULL)  //abrir archivo para leer (r)
  8. {        
  9. //si no se puede abrir es porque no existe. (si fuera apertura para
  10. //escritura: fopen(&#34;archivo&#34;,&#34;w&#34;) si no existiera el archivo se crearía)
  11. printf(&#34;&#092;n&#092;t&#092;aERROR: no se ha encontrado el archivo&#34;);//mostrar error por pantalla
  12. exit(1);//finalizar
  13. }
  14.  
  15. while(!feof(pf))//mientras no se llegue al final del fichero
  16. {
  17. fscanf(pf,&#34;%d&#092;n&#34;,&a); //leer del fichero
  18. fprintf(&#34;%d&#092;n&#34;,a);//mostrar por pantalla lo leido
  19. }
  20. }
  21.  
  22.  
Espero qu esté bien (no lo he comprobado) y que te sirva de ayuda...
Hay muchas formas de acceder a un archivo:
lectura: r (si el archivo no existe no se crea)
lectura/escritura: r+
escritura: w (si el archivo existe borra lo que tenía y si no existe lo crea)
escritura/lectura: w+
añadir datos: a (si el archivo no existe lo crea y si existe añade informacion al final)
añadir/leer: a+

Además existen varias maneras de acceder al texto:
fprintf y fscanf: escriben y leen informacion de un archivo con formato (modo texto).
fputs y fgets: escriben y leen cadenas de caracteres de un archivo (modo texto)
fputc y fgetc: escriben y leen caracter a caracter de un archivo (modo texto)
putw y getw: escriben y leen palabra a palabra (modo binario)
fread y fwrite: escriben y leen en ficheros a partir de estructuras (modo binario)

Bueno con esto yo creo que podrás empezar a hacer algo más...
Suerte!
Título: Re: Imprimir En Tu Prog. El Contenido De Un Fichero
Publicado por: carmamezo en Viernes 27 de Febrero de 2004, 14:28
perdon... hay un fallo en el último fprintf, debería ser printf. Para mostrar texto en pantalla. SORRY :whistling:
Título: Re: Imprimir En Tu Prog. El Contenido De Un Fichero
Publicado por: amedinadiaz en Viernes 27 de Febrero de 2004, 16:17
Gracias x la ayuda, al final encontre una manera de hacerlo que se ajustaba a lo que me pedian y que os dejo aqui (seguramente hay formas mas faciles y rapidas pero no podia usarlas):

Código: Text
  1.  
  2. **************************************************************/
  3. /* Authors: Antonio Medina, Paul Griffiths and Clarisse Smith */
  4. /* Date: 24-2-04                                              */
  5. /* EE1K2: STRUCTURED SOFTWARE DESIGN                          */
  6. /* ESA GROUP                                                  */
  7. /* GROUP ORANGE - OBJECT MANAGER MODULE                       */
  8. /**************************************************************/
  9.  
  10. #include &#60;stdio.h&#62;
  11. #include &#60;stdlib.h&#62; //Including this library in order to use the 'malloc' function.
  12. #include &#60;string.h&#62; //Including this library in order to use the 'strcpy' and the
  13.         //'strlen' functions.
  14.  
  15. struct object2 //Creating a structure which contains all the info about the object in the map.
  16. {
  17.     int* objtype;
  18.     int* objid;
  19.     int* gridx;
  20.     int* gridy;
  21.     int* moveable;
  22.     int* passable;
  23.     int* live;
  24.     int* health;
  25. };
  26.  
  27. struct object //Creating another structure to store the object type, name and description.
  28. {
  29.     int* objtype;
  30.     char** objname;
  31.     char** objdesc;
  32. };
  33.  
  34. void object_type_name_description(struct object *p1) //Creating a function to print the object
  35. {              //type, name and description.
  36.     FILE *obj_name_desc; //Declaring the file
  37.     char buffer[3][100]; //This buffer will store all the temporary data.
  38.     int i, scan, length;
  39.  
  40.     obj_name_desc=fopen(&#34;objname.txt&#34;,&#34;r&#34;); //Opening the file
  41.  
  42.     //Allocating memory for the object type, name and description.
  43.     p1-&#62;objtype=(int*)(malloc(17*sizeof(int)));
  44.     p1-&#62;objname=(char**)(malloc(17*sizeof(char*)));
  45.     p1-&#62;objdesc=(char**)(malloc(17*sizeof(char*)));
  46.  
  47.     for(i=0; (i&#60;17)||(scan==EOF); i++)
  48.     {
  49.   scan=fscanf(obj_name_desc,&#34;%s %s %s&#34;, buffer[0], buffer[1], buffer[2]); //Scaning from
  50.                         //the file.
  51.   p1-&#62;objtype[i]=atoi(buffer[0]); //Converting strings into integers.
  52.  
  53.   length=strlen(buffer[1]);
  54.   p1-&#62;objname[i]=(char*)(malloc(length*sizeof(char)));
  55.   strcpy(p1-&#62;objname[i], buffer[1]); //Copying from buffer to objname.
  56.  
  57.   length=strlen(buffer[2]);
  58.   p1-&#62;objdesc[i]=(char*)(malloc(length*sizeof(char)));
  59.   strcpy(p1-&#62;objdesc[i], buffer[2]); //Copying from buffer to objname.
  60.  
  61.  
  62.     }
  63.     for(i=0; i&#60;17; i++)
  64.     printf(&#34;%d %s %s&#092;n&#34;, p1-&#62;objtype[i], p1-&#62;objname[i], p1-&#62;objdesc[i]);
  65.  
  66. }
  67. void object_id (struct object2 *p2) //Creating another function to show type, id, gridx, gridy,
  68. {           //moveable, passable, live and health.
  69.     int i, scan;
  70.     char buffer2[7][10];
  71.     FILE *object_id;
  72.  
  73.     object_id=fopen(&#34;objstruct.txt&#34;, &#34;r&#34;);
  74.  
  75.     //Allocating memory.
  76.     p2-&#62;objtype=(int*)(malloc(64*sizeof(int)));
  77.     p2-&#62;objid=(int*)(malloc(64*sizeof(int)));
  78.     p2-&#62;gridx=(int*)(malloc(64*sizeof(int)));
  79.     p2-&#62;gridy=(int*)(malloc(64*sizeof(int)));
  80.     p2-&#62;moveable=(int*)(malloc(64*sizeof(int)));
  81.     p2-&#62;passable=(int*)(malloc(64*sizeof(int)));
  82.     p2-&#62;live=(int*)(malloc(64*sizeof(int)));
  83.     p2-&#62;health=(int*)(malloc(64*sizeof(int)));
  84.  
  85.     for(i=0; ((i&#60;139)||(scan==EOF)); i++)
  86.     {
  87.   scan=fscanf(object_id, &#34;%s %s %s %s %s %s %s %s&#34;, buffer2[0], buffer2[1],
  88.     buffer2[2], buffer2[3], buffer2[4], buffer2[5], buffer2[6], buffer2[7]);
  89.  
  90.   //Converting strings into integers.
  91.   p2-&#62;objtype[i]=atoi(buffer2[0]);
  92.   p2-&#62;objid[i]=atoi(buffer2[1]);
  93.   p2-&#62;gridx[i]=atoi(buffer2[2]);
  94.   p2-&#62;gridy[i]=atoi(buffer2[3]);
  95.   p2-&#62;moveable[i]=atoi(buffer2[4]);
  96.   p2-&#62;passable[i]=atoi(buffer2[5]);
  97.   p2-&#62;live[i]=atoi(buffer2[6]);
  98.   p2-&#62;health[i]=atoi(buffer2[7]);
  99.  
  100.   printf(&#34;%d %d %d %d %d %d %d %d&#092;n&#34;, p2-&#62;objtype[i], p2-&#62;objid[i], p2-&#62;gridx[i],
  101.     p2-&#62;gridy[i], p2-&#62;moveable[i], p2-&#62;passable[i], p2-&#62;live[i], p2-&#62;health[i]);
  102.     }
  103. }  
  104.  
  105.  
  106. int main (void)
  107. {
  108.     struct object A;
  109.     struct object2 B;
  110.  
  111.    
  112.     object_type_name_description(&A);
  113.     printf(&#34;&#092;n&#34;);
  114.     object_id(&B);
  115.    
  116.  
  117.     return 0;
  118. }
  119.  
  120.  

Salu2!!