Reputation: 3
I have to modify a string in a file that is structure in this way:
Name: Name1
Surname: Surname1
ID: 00000000
Age: 30
Name: Name2
Surname: Surname2
ID: 00000001
Age: 32
...
I think to do in this way: I ask in input the ID, I ask what he wants to change (if it is name, surname, ID or age) and then I ask with what he wants to change it. Then I search the ID in the file and if he wants to change the surname I move the FSEEK to -1, for the name I move the FSEEK to -2 or I move the FSEEK to +1 if he wants to change the age.
So, is there a easier o more quick way to do this?
Thank you :)
Upvotes: 0
Views: 580
Reputation: 1
You cannot insert or delete some sequence of bytes inside a file. You can only overwrite existing bytes, or append new bytes at end of file (this is how <stdio.h>
files have been standardized, and how POSIX or Windows files behave, and how almost every file system -I don't know of any exception today- works)
So you could produce a new file from the old one (then perhaps rename
the new as the old).
You could also read all the file in memory and output the entire new content from memory.
You probably should consider higher-level abstractions: indexed files à la GDBM or simple databases à la Sqlite (or real databases like PostgreSQL, MongoDb, etc...)
Notice that current processors are much faster than disks (nearly a million times for hard spinning disks - with access times in dozen of milliseconds - , and probably thousand times for SSD - with access times of about a hundred microseconds). So it makes a lot of sense (and much more than in previous century) to spend some CPU time to "organize" data written to "files" or to the "network".
If working with a laptop or desktop, it has a lot of RAM today (several gigabytes), so it is very likely that all of your data fits in memory. Also RAM bandwidth is much higher than disk, or SSD, or network bandwidth (and the RAM latency is much lower too). If you manage a lot of data (more than a gigabyte) using a database system is sensible (in particular, because you might not write all of it at once).
You might be interested in serialization, application checkpointing, JSON ....
Upvotes: 2
Reputation: 621
That means you would have to open the file for both reading and writing at the same time, which has a few complications which aren't worth it, in your case.
I would rather do the following:
Upvotes: 1