Reputation: 982
Alright, this maybe the simplest (or the stupidest) question, but I just got to know...
Suppose I have a text file containing account no. and balance. I am writing a program to search the file using entered account no. and update the balance field in the same text file with a new balance. I am finding it surprisingly difficult to do so using file streams. The problem is that I am trying to overwrite the balance string in the said text file with a new balance string.
So, if the balance is 1000 (4 digits), I can overwrite it with another 4 digit string. But, if the new balance string is more than 4 digits, it is overwriting the data after the balance field (it is a simple text file mind you...). For example, if the text file contains
Acc. No. balance
123456 100
123567 2500
The fields are separated by TAB '\t' character, and next record is separated by a newline '\n'. If I enter new deposit of 200000 for account 123456, the fwrite() function overwrites the data in the text file as...
Acc. No Balance
123456 2001003567 2500
You can notice that the '\n' after the balance field, and 2 digits from the next accounts' acc. no. is overwritten.
Of course, no-one wants that to happen :) What I need is a way to insert text in that file, not just overwrite it. There are many results of doing this using Java, python or even SED, but nothing using FILE streams. Please share your thoughts... thanks.
Upvotes: 0
Views: 454
Reputation: 10383
If you really want to manage your data in a plain text file:
While you are reading the file in, write a modified version of your data into a temporary file, then delete the original file and rename the temp file to the original filename. But be carefull that no other process accesses the same file concurrently.
Database systems were invented for such purposes. So I recommend to manage your data in a database table and dynamically create a text report when needed.
Upvotes: 0
Reputation: 36059
You'll have to move all data after the insertion point a few bytes up first. That's what Java, sed or python do as well, if they aren't writing a temporary file to begin with.
Upvotes: 1