Programación General > C/C++

 Imprimir En Tu Prog. El Contenido De Un Fichero

(1/1)

amedinadiaz:
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!

nicokiki:
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

carmamezo:
Bueno... aki te mando un ejemplo en C:

--- Código: Text --- Void main(){FILE *pf;int a; if((pf=fopen(&#34;archivo&#34;,&#34;r&#34;))==NULL)  //abrir archivo para leer (r){         //si no se puede abrir es porque no existe. (si fuera apertura para //escritura: fopen(&#34;archivo&#34;,&#34;w&#34;) si no existiera el archivo se crearía)printf(&#34;&#092;n&#092;t&#092;aERROR: no se ha encontrado el archivo&#34;);//mostrar error por pantallaexit(1);//finalizar} while(!feof(pf))//mientras no se llegue al final del fichero{fscanf(pf,&#34;%d&#092;n&#34;,&a); //leer del ficherofprintf(&#34;%d&#092;n&#34;,a);//mostrar por pantalla lo leido}}  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!

carmamezo:
perdon... hay un fallo en el último fprintf, debería ser printf. Para mostrar texto en pantalla. SORRY :whistling:

amedinadiaz:
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 --- **************************************************************//* Authors: Antonio Medina, Paul Griffiths and Clarisse Smith *//* Date: 24-2-04                                              *//* EE1K2: STRUCTURED SOFTWARE DESIGN                          *//* ESA GROUP                                                  *//* GROUP ORANGE - OBJECT MANAGER MODULE                       *//**************************************************************/ #include &#60;stdio.h&#62;#include &#60;stdlib.h&#62; //Including this library in order to use the 'malloc' function.#include &#60;string.h&#62; //Including this library in order to use the 'strcpy' and the        //'strlen' functions. struct object2 //Creating a structure which contains all the info about the object in the map.{    int* objtype;    int* objid;    int* gridx;    int* gridy;    int* moveable;    int* passable;    int* live;    int* health;}; struct object //Creating another structure to store the object type, name and description. {    int* objtype;    char** objname;    char** objdesc;}; void object_type_name_description(struct object *p1) //Creating a function to print the object{              //type, name and description.    FILE *obj_name_desc; //Declaring the file    char buffer[3][100]; //This buffer will store all the temporary data.    int i, scan, length;     obj_name_desc=fopen(&#34;objname.txt&#34;,&#34;r&#34;); //Opening the file     //Allocating memory for the object type, name and description.    p1-&#62;objtype=(int*)(malloc(17*sizeof(int)));    p1-&#62;objname=(char**)(malloc(17*sizeof(char*)));    p1-&#62;objdesc=(char**)(malloc(17*sizeof(char*)));     for(i=0; (i&#60;17)||(scan==EOF); i++)    {  scan=fscanf(obj_name_desc,&#34;%s %s %s&#34;, buffer[0], buffer[1], buffer[2]); //Scaning from                        //the file.  p1-&#62;objtype[i]=atoi(buffer[0]); //Converting strings into integers.   length=strlen(buffer[1]);  p1-&#62;objname[i]=(char*)(malloc(length*sizeof(char)));  strcpy(p1-&#62;objname[i], buffer[1]); //Copying from buffer to objname.   length=strlen(buffer[2]);  p1-&#62;objdesc[i]=(char*)(malloc(length*sizeof(char)));  strcpy(p1-&#62;objdesc[i], buffer[2]); //Copying from buffer to objname.      }    for(i=0; i&#60;17; i++)    printf(&#34;%d %s %s&#092;n&#34;, p1-&#62;objtype[i], p1-&#62;objname[i], p1-&#62;objdesc[i]); }void object_id (struct object2 *p2) //Creating another function to show type, id, gridx, gridy,{           //moveable, passable, live and health.    int i, scan;    char buffer2[7][10];    FILE *object_id;     object_id=fopen(&#34;objstruct.txt&#34;, &#34;r&#34;);     //Allocating memory.    p2-&#62;objtype=(int*)(malloc(64*sizeof(int)));    p2-&#62;objid=(int*)(malloc(64*sizeof(int)));    p2-&#62;gridx=(int*)(malloc(64*sizeof(int)));    p2-&#62;gridy=(int*)(malloc(64*sizeof(int)));    p2-&#62;moveable=(int*)(malloc(64*sizeof(int)));    p2-&#62;passable=(int*)(malloc(64*sizeof(int)));    p2-&#62;live=(int*)(malloc(64*sizeof(int)));    p2-&#62;health=(int*)(malloc(64*sizeof(int)));     for(i=0; ((i&#60;139)||(scan==EOF)); i++)    {  scan=fscanf(object_id, &#34;%s %s %s %s %s %s %s %s&#34;, buffer2[0], buffer2[1],    buffer2[2], buffer2[3], buffer2[4], buffer2[5], buffer2[6], buffer2[7]);   //Converting strings into integers.  p2-&#62;objtype[i]=atoi(buffer2[0]);  p2-&#62;objid[i]=atoi(buffer2[1]);  p2-&#62;gridx[i]=atoi(buffer2[2]);  p2-&#62;gridy[i]=atoi(buffer2[3]);  p2-&#62;moveable[i]=atoi(buffer2[4]);  p2-&#62;passable[i]=atoi(buffer2[5]);  p2-&#62;live[i]=atoi(buffer2[6]);  p2-&#62;health[i]=atoi(buffer2[7]);   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],    p2-&#62;gridy[i], p2-&#62;moveable[i], p2-&#62;passable[i], p2-&#62;live[i], p2-&#62;health[i]);    }}     int main (void){    struct object A;    struct object2 B;         object_type_name_description(&A);    printf(&#34;&#092;n&#34;);    object_id(&B);         return 0;}  
Salu2!!

Navegación

[0] Índice de Mensajes

Ir a la versión completa