Hello all,
How can I open a file in asynchronous mode in a console application? I would like to open both ASCII and BINARY files, but first an ASCII file. Thank you for your time.
I only know the answer for Windows, but since you did not ask in the Windows Programming forum, I am not sure if my answer will be good for you. Drop a line if I should post.
You can either use the ReadFile() or ReadFileEx() functions. You need to provide an OVERLAPPED structure. The structure will provide the function call with a callback function that will be called once the file read is complete.
The catch: In order for the callback function to be called, the calling thread (the one that called ReadFile() or ReadFileEx()) has to be in an alertable state. You can read more about the alertable state and Asynchonous Procedure Call if you read the MSDN library help topic for the function QueueUserAPC() (http://msdn.microsoft.com/en-us/library/ms684954%28VS.85%29.aspx).
Basically, you use one of the extended wait functions enumerated in that webpage to suspend the thread and wait for the read function call to call the callback function.
That would be the single-threaded asynchonous approach.
As usual, you can also spawn a new thread and call ReadFie() from that second thread and make the call synchronous. The new thread will be blocked, but the main thread will be free. All you have to do afterwards is synchronize both threads using a synchronization object, such as an event. Personally, I would go for this one for a console application. I would only consider the APC solution for a windows GUI application where you use MsgWaitForMultipleObjectsEx() in the main message pump as opposed to the usual GetMessage() function call.
Hello webJose
Thank you very much for your post. It is indeed clear and I will go through the link to learn more. I am not an experienced programmer and I have never used threads so far, though I am eagerly looking forward to using threads.