How to modify data from a C record?

1

Well that, how can I modify data from a record, I was trying this way:

    gets(search); // nombre del dato que queremos modificar
    fread(&producto,sizeof(_Registro),1,pf);
        while(!feof(pf)){
            if (strcmp(search,producto.nombre)==0){ //aqui obtenemos el dato en el fichero en la posición en la que se encuentra.

                printf("Nombre del Producto %s\n",producto.nombre); //lo imprimimos
                printf("Nuevo Nombre del Producto: ");
                gets(producto.nombre); //pido el nuevo nombre
                fflush(stdin);                  
                fwrite(&producto,sizeof(_Registro),1,pf); // y sobre escribo el fichero
            }

but do not overwrite it: /, I have looked for how to do it in another way but I have not achieved success, thank you in advance and greetings.

    
asked by Angel Valenzuela 10.04.2016 в 18:36
source

1 answer

1
fread(&producto,sizeof(_Registro),1,pf);
while(!feof(pf)){

If fread is outside the loop, you will not do more than a single reading, then the only thing your program can do is compare that record again and again, which smells like an infinite loop.

On the other hand, once you have made a reading the internal pointer of the file changes its position. If your idea is to overwrite the data you will have to reverse the pointer. To do this you can look at ftell , to know the position within the file and fseek to change the position of the pointer.

And, to top it off, you should know that fflush should only be used to process output buffers and in fflush(stdin) , stdin is an input buffer. In this case the result is indeterminate, then it does not seem a good idea to trust that function works correctly.

    
answered by 11.04.2016 в 09:44