Current position in the file - C

Asked

Viewed 657 times

3

Hello, I’m having a question about C file manipulation and I’m not getting the answer to that. I am recording an "a" record of type "Student" in a binary file "archiving":

    fwrite(&a, sizeof(Aluno), 1, arquivoBinario);

I know that fução returns the number of elements that were written successfully in the file. What I’d like to know is in what position in the file that record was written.

I need this position to make a quick access to this record that was saved in this file without having to search for all sequentially.

I’m sorry for any error in posting and please correct me, it’s my first question here.

1 answer

2


The function fwrite writes at the current position at which the file goes and modifies that position X bytes forward according to the bytes that have been written.

The current position in the file is controlled by previous writings and readings, made with fwrite and fread respectively.

What I’d like to know is in what position in the file that record was written

Before writing we can consult the current position with ftell:

long posicao = ftell (arquivoBinario);

And it will be from that byte that the data will be written.

I need this position to make a quick access to this record that was saved in that file without having to search for all sequentially

To modify directly the current position in the file we can use fseek, as follows:

fseek (arquivoBinario, 10 , SEEK_SET); 
/*fseek(arquivo,byte a posicionar,do inicio);*/ 

Here we see that it receives the file, followed by the amount of bytes and the positioning mode, in which the SEEK_SET refers from the beginning. The previous example places the file at the tenth byte from the beginning.

Alternatively we can use SEEK_END as last parameter if we want to position from the end.

  • Thank you very much. It seems very simple I think I was not knowing how to look for the solution but solved my problem perfectly. Vlw himself.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.