Test Foro de elhacker.net SMF 2.1

Programación => Programación C/C++ => Mensaje iniciado por: mapers en 1 Abril 2011, 17:13 PM

Título: Error Fichero
Publicado por: mapers en 1 Abril 2011, 17:13 PM
Buenas señores estoy trabajando con archivos de texto plano ...pero con este tipo de estructuras me sale todo bien.... lo unico que no me sale es cuando llamo al fichero e ingresoi nuevos reportes chanca los datos que hay ,lo que  deberia hacer es  ingresar y lguardarlos  cpon los anteriores a ver si me dan una mano y me dicen el error
Código (cpp) [Seleccionar]

# define DELIM_C "@"
# define DELIM_R "*"

//-------------------------------------------------//
//-------------------------------------------------//

#include <stdio.h>
#include <iostream>
#include <conio.h>
# include <io.h>
# include <fcntl.h>
# include <sys\stat.h>


//-------------------------------------------------//
//-------------------------------------------------//

using namespace std;

int fichero;
char nom[10];
int edad;
char nombre[10];

//-------------------------------------------------//
//-------------------------------------------------// 

void crear(char nombre[30])
{
fichero= creat( nombre , S_IWRITE | S_IREAD );

if ( fichero < 0 )
    {
      printf(" El Archivo No se Pudo crear !!! ");
       getch();
      return;     
    }
   
else
    printf(" \t\t\t El Archivo Se Creo Correctamente !!!! "); 
     getch();
}

//-------------------------------------------------//
//-------------------------------------------------//


void abrir(char nombre[30])
{
fichero = open ( nombre , O_RDWR);
 
   if ( fichero < 0 )
      printf(" El Archivo No se Pudo Abrir !!! ");
}

//-------------------------------------------------//
//-------------------------------------------------//

void escribir(int N)
{
abrir(nombre);
printf("\n");
printf("\t Ingrese sus Datos ......  \n");
getch();

for(int j=1;j<=N;j++)
   {
    fflush(stdin);
    cout<<endl;
    printf("  -->  Ingrese Nombre   : ");
    fflush(stdin);
    gets(nom);
   
    printf("  --> Ingrese Edad     : ");
    fflush(stdin);
    cin>>edad;
    fflush(stdin);
   
   
    write( fichero, nom , strlen(nom) );
    write( fichero , DELIM_C , 1 );
    write( fichero , &edad , 2 );
    write( fichero, DELIM_R , 1 );
  }

  close(fichero);

}

//-------------------------------------------------//
//-------------------------------------------------//

void leer()
{
  char K;
  int i = 0;
   printf("\nTeclee El nombre del Fichero a Acceder ");
   fflush(stdin);
   gets(nombre);
   abrir(nombre);

  while ( read ( fichero , &K , 1 ) > 0 )
        {
         if( K == '*' ) 
           {
            printf("\t\t    ");
            printf("\n");
            continue;
           }
           
         if( K == '@' ) 
           {
           printf("  ");
            read(fichero,&edad,2);
            cout<<edad;
           continue;
           }
           
            cout<<K;
        }
getch();
close(fichero);

}
//-------------------------------------------------//
//-------------------------------------------------//

void menu()
{
  printf("\n");
  system("cls"); 
  printf("\n");
  system("color a");
  printf("\t ÈÍÍÍÍÍÍÍÍÍÍÍÍ<< Reguistros de Longitud Variable >>ÍÍÍÍÍÍÍÍÍÍͼ\n");
  printf("\n\t\t º º     MENU           ");
  printf("\n\t\t º º                      ");
  printf("\n\t\t º º1.  Crear fichero            ");
  printf("\n\t\t º º2.  Insertar datos         ");
  printf("\n\t\t º º3.  Abrir y leer datos Guardados             ");
  printf("\n\t\t º º4.  Salir           \n");
  printf("\t\t º º\n");
  printf("\t\t ÈÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍͼ\n");

}


//-------------------------------------------------//
//-------------------------------------------------//
   

int main()
{


int N;

int opcion; 
menu();
   
while(1)
{
   printf("\n\n");

   printf("\n");
   for(int j=0;j<10;j++)
   {
   menu();
   }
   //leer();
   
   do
    {

     printf("\n\n   -> Ingrese una Opcion");
     printf("      --------------->  ");
     cin>>opcion;

    }

  while(opcion < 1 || opcion > 4);

switch (opcion)
{
  case 1:     
            printf("\n\tIngrese el nombre del Fichero ");
             fflush(stdin);
            gets(nombre);
            crear(nombre);
            break;

  case 2:
            cout<<endl<<"   - Cantidad de Datos : ";
            cin>>N;
            escribir(N);
            break;

  case 3:
            leer();
            break;
       
  case 4:
       
            printf("\n\t      *****  Se Guardaran los cambios ****" );
            printf("\n\n\n");
            getch();
           exit(0);
            break;
   default:
           printf("\nopcion no valida");
}
}

printf("\n\n\n");
               
system("pause");
}

//-------------------------------------------------//
//-------------------------------------------------//






Título: Re: Error Fichero
Publicado por: Leber en 1 Abril 2011, 18:40 PM
Hola,

Te esta machacando los datos, y no te guarda los anteriores, porque estas abriendo el fichero por el principio. Si miras la documentacion de "open", vemos que el flag O_APPEND dice:


O_APPEND
              The file is opened in append mode.  Before each write(2), the file offset is positioned at the end of the file, as if with lseek(2).  O_APPEND  may  lead  to  cor‐
              rupted  files on NFS file systems if more than one process appends data to a file at once.  This is because NFS does not support appending to a file, so the client
              kernel has to simulate it, which can't be done without a race condition.


Saludos
Título: Re: Error Fichero
Publicado por: mapers en 1 Abril 2011, 20:38 PM
entonces como haria ???? una manitaaa...........
Título: Re: Error Fichero
Publicado por: Leber en 2 Abril 2011, 01:22 AM
Le tienes que pasar el flag O_APPEND a la funcion open.

open( path, O_RDWR | O_APPEND)