------ 文章開始 ------

#include <iostream>
#include <sys/types.h>
#include <aio.h>
#include <fcntl.h>
#include <errno.h>

using namespace std;

const int SIZE_TO_READ = 100;

int main()
{
    // open the file
    int file = open("data.txt", O_RDONLY, 0);

    if (file == -1)
    {
        cout << "Unable to open file!" << endl;
        return 1;
    }

    // create the buffer
    int* buffer = new int[SIZE_TO_READ];    //although the data is void

    // create the control block structure
    aiocb cb;

    memset(&cb, 0, sizeof(aiocb));
    cb.aio_nbytes = SIZE_TO_READ;
    cb.aio_fildes = file;
    cb.aio_offset = 0;
    cb.aio_buf = buffer;

    unsigned long long int sum(0);

    // read!
    while(1)
    {
        if (aio_read(&cb) == -1)
        {
            cout << "Unable to create request!" << endl;
            close(file);
            break;
        }
        for(int i=0; i<100; i++)
            sum+ = (unsigned long long int)cb.aio_buf[i];
    }

    cout << "Request enqueued!" << endl;

    // wait until the request has finished
    while(aio_error(&cb) == EINPROGRESS)
    {
        cout << "Working..." << endl;
    }

    // success?
    int numBytes = aio_return(&cb);

    if (numBytes != -1)
    {
        cout << "Success!" << endl;
        cout << "sum = " << sum << endl;
    }
    else
        cout << "Error!" << endl;

    // now clean up
    delete[] buffer;
    close(file);

    return 0;
}
------ 文章結尾 ------

[複製網址] [開新視窗] [檢舉短網址] [QR條碼]

服務條款 - 加入會員(免費) - 回報問題網址 - 聯絡偶們 -

© 2025 PPT.cc