Questioneer
Questioneer

Reputation: 793

Can you write from a particular position in a file from c?

I want to start at a particular offset, write and then at some point read from that same offset and confirm I read what I wrote to the file. The file is in binary. I'm confident I need to use fseek but I may want to call a write several times prior to reading the whole file.

write(unsigned long long offset, void* pvsrc, unsigned long long nbytes)

 pFile = fopen("D:\\myfile.bin","wb"); 

 fseek(pFile,offset,SEEK_SET);   
 WriteResult = fwrite (pvsrc, 1, nbytes, pFile); 
 fclose(pFile);

Anyone see any issue with this? .. Anyone?

Upvotes: 2

Views: 3039

Answers (2)

tdenniston
tdenniston

Reputation: 3519

If you are on Linux, you can use the pread() and pwrite() functions: http://linux.die.net/man/2/pread

If you are on Windows, you can use the ReadFile() and WriteFile() functions with the lpOverlapped parameter: http://msdn.microsoft.com/en-us/library/aa365467%28VS.85%29.aspx

Upvotes: 1

Michael Goldshteyn
Michael Goldshteyn

Reputation: 74390

You can use ftell() to tell you your current position in the file, perform some writes and then fseek() to the starting position you got with ftell() to read the data that you wrote.

Upvotes: 3

Related Questions