Tuesday, July 14, 2009

File handling in C: How to edit existing Binary File(Not Append)?

Any one PLS Help Me!! (Urgent)





I want to edit the contents of a structure I've written to a file(Turbo C). And I have to save it too. PLS help me out..........





The purpose is 'edit' option in a phone book application in Turbo C.

File handling in C: How to edit existing Binary File(Not Append)?
A phone book application should have a database-like structure. You'll be writing to offsets and only certain amounts of data that fit the field sizes. At least, if you're writing data to the structure. If you're changing the structure best is to create a new file with that structure and copy the data over, deleting the old file.
Reply:you can use fseek() to go to a certain position in the file, and then fwrite() to write a record.





you have to calculate the position in fseek; if your file only has structures which have the same file, it's easy. then the position is sizeof(structure) * index.
Reply:The Binary/Text file dichotomy is Windows-specific, meaning that other operating systems just have you open the file, perform functions on it and close it and it doesn't matter what type of file it is. Even in Windows, the difference is not as important as understanding what is in either file.





Obviously you want to search for the proper struct, copy it to memory edit it and rewrite it. The first thing to do is to find the struct. If you know the size of the struct (which you should) and the number of the record you should be able to determine its position in the file. If you have to find the record, you can search for the relevant information however you choose, copy the file position of the start of the struct into a separate variable, copy the struct into a copy in memory, and so on, resetting the position of the file pointer to that of the variable you saved the start position into.





Frankly, you might as well just copy the whole database into memory, into an array if you can't deal with linked lists and other data structures, edit it, and write the whole file back to disk destructively. But if that's how they want you to do it that's how you should do it.


No comments:

Post a Comment