LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   C: Manipulating file adresswise (https://www.linuxquestions.org/questions/programming-9/c-manipulating-file-adresswise-867204/)

derchris 03-08-2011 08:08 AM

C: Manipulating file adresswise
 
Hey,

I'm looking for a special fileoperation. As we know, we can open a file as FILE * and than handle it as a stream. The problem is: In that way I can write and read only at the beginning (or write at the end).
But want I want to do, is to manipulate a special point within the file.
Example:
Assume my file stars at address 0, then I want to insert my 10 byte values at offset 526, so I only overwrite byte 526-536 and let the rest of the file unchanged.

The only idea I came up with was the read the whole file, write it back into a new file (with the sections I wanted being changed) and then delete the old file and replace it with the new one. But this solution is not very elegant.
So I wonder whether there is a better solution for me.
All I need is actually an address/pointer to the beginning of the file. Using memcpy it should not be a problem to overwrite the part of the file then.
Note: I'm not talking about textfiles, but binaries.

johnsfine 03-08-2011 08:12 AM

start with
Code:

man fseek
Read that and some of the other functions pointed to from there. That should give you a good idea of your choices using file I/O.

http://www.cplusplus.com/reference/c.../cstdio/fseek/

Quote:

Originally Posted by derchris (Post 4282720)
All I need is actually an address/pointer to the beginning of the file. Using memcpy it should not be a problem to overwrite the part of the file then.

That is also possible (map a file into your process's address space, so you can read and write it as memory). I'm guessing that isn't best for your needs. But if you think it might be, look at the man page for mmap.

I also did a google search for "mmap examples" and the top choice was this thread at LQ
http://www.linuxquestions.org/questi...5/#post2547332

derchris 03-08-2011 09:17 AM

Thank you, I guess using fseek I'll get the job done pretty easily :)


All times are GMT -5. The time now is 08:11 AM.