Do you have a question? Post it now! No Registration Necessary. Now with pictures!
- Posted on
- Simultaneous writing and reading of a file.
April 24, 2005, 1:05 pm
rate this thread
I would like to solve the following problem. On the server side I have
a file with a sequence of natural numbers (1, 2, 3, 4, 5, ...., n).
Each user, after some action, adds new number (n+1, where n is the last
number in the file) to the end of file. To do this user has to open the
file for reading, read the last number, perform corresponding
manipulations with the extracted last number and add result to the end
of the file (after opening it for adding). However, it can happens that
during one user performs algebraic calculation with the last extracted
number, some another user opens the file with numbers, performs the
same algebraic manipulation, and adds result to the end of file.
Afterwards, the first user finishes his calculation and adds the same
number to the file. I would like to avoid this situation. My solution
is to keep file opened during algebraic calculations. It is the
sequence should be the following. Open file, read the last number, with
the usage of the last number calculate next number, add this new
calculated number to the end of the file, close the file.
The first my question is whether one can do it. I mean can one open
file for both reading and adding? If yes, how one need to do it? And
the last question is whether it helps to solve my problem? I mean, is
it thru that during file is opened by one user, another user cannot
read and change this file?
- R. Rajesh Jeba Anbiah
April 24, 2005, 1:56 pm
Re: Simultaneous writing and reading of a file.
What you have is a database situation.
Unless you use an RDBMS you must either lock the file from the
time it is read for update until it is written at the end of the
transaction. As I am sure you have already discovered the users
of such systems aren't very cooperative. They tend to start
transactions and then answer the phone, go to lunch, take a
coffee break, etc. before completing their transactions.
IMHO the best solution is to use an RDBMS, MySQL, for example,
which supports auto-increment columns. With auto-increment when
row is added to the database table the auto-increment column is
incremented by the RDBMS. As a result it is not necessary for
the application to read the table prior to the calculation being
made and your problem goes away.