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("archivo","r"))==NULL) //abrir archivo para leer (r){ //si no se puede abrir es porque no existe. (si fuera apertura para //escritura: fopen("archivo","w") si no existiera el archivo se crearía)printf("\n\t\aERROR: no se ha encontrado el archivo");//mostrar error por pantallaexit(1);//finalizar} while(!feof(pf))//mientras no se llegue al final del fichero{fscanf(pf,"%d\n",&a); //leer del ficherofprintf("%d\n",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 <stdio.h>#include <stdlib.h> //Including this library in order to use the 'malloc' function.#include <string.h> //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("objname.txt","r"); //Opening the file //Allocating memory for the object type, name and description. p1->objtype=(int*)(malloc(17*sizeof(int))); p1->objname=(char**)(malloc(17*sizeof(char*))); p1->objdesc=(char**)(malloc(17*sizeof(char*))); for(i=0; (i<17)||(scan==EOF); i++) { scan=fscanf(obj_name_desc,"%s %s %s", buffer[0], buffer[1], buffer[2]); //Scaning from //the file. p1->objtype[i]=atoi(buffer[0]); //Converting strings into integers. length=strlen(buffer[1]); p1->objname[i]=(char*)(malloc(length*sizeof(char))); strcpy(p1->objname[i], buffer[1]); //Copying from buffer to objname. length=strlen(buffer[2]); p1->objdesc[i]=(char*)(malloc(length*sizeof(char))); strcpy(p1->objdesc[i], buffer[2]); //Copying from buffer to objname. } for(i=0; i<17; i++) printf("%d %s %s\n", p1->objtype[i], p1->objname[i], p1->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("objstruct.txt", "r"); //Allocating memory. p2->objtype=(int*)(malloc(64*sizeof(int))); p2->objid=(int*)(malloc(64*sizeof(int))); p2->gridx=(int*)(malloc(64*sizeof(int))); p2->gridy=(int*)(malloc(64*sizeof(int))); p2->moveable=(int*)(malloc(64*sizeof(int))); p2->passable=(int*)(malloc(64*sizeof(int))); p2->live=(int*)(malloc(64*sizeof(int))); p2->health=(int*)(malloc(64*sizeof(int))); for(i=0; ((i<139)||(scan==EOF)); i++) { scan=fscanf(object_id, "%s %s %s %s %s %s %s %s", buffer2[0], buffer2[1], buffer2[2], buffer2[3], buffer2[4], buffer2[5], buffer2[6], buffer2[7]); //Converting strings into integers. p2->objtype[i]=atoi(buffer2[0]); p2->objid[i]=atoi(buffer2[1]); p2->gridx[i]=atoi(buffer2[2]); p2->gridy[i]=atoi(buffer2[3]); p2->moveable[i]=atoi(buffer2[4]); p2->passable[i]=atoi(buffer2[5]); p2->live[i]=atoi(buffer2[6]); p2->health[i]=atoi(buffer2[7]); printf("%d %d %d %d %d %d %d %d\n", p2->objtype[i], p2->objid[i], p2->gridx[i], p2->gridy[i], p2->moveable[i], p2->passable[i], p2->live[i], p2->health[i]); }} int main (void){ struct object A; struct object2 B; object_type_name_description(&A); printf("\n"); object_id(&B); return 0;}
Salu2!!
Navegación
Ir a la versión completa