Advanced Programming in UNIX Environment Episode 80

#include "apue.h"
#include 
#include 
#include 
#include 

#define BSZ 4096
#define NBUF 8

enum rwop
{
    UNUSED=0,
    READ_PENDING=1,
    WRITE_PENDING=2
};

struct buf
{
    enum rwop op;
    int last;
    struct aiocb aiocb;
    unsigend char data[BSZ];
}

unsigned buf bufs[NBUF;

unsigned char translate(unsigned char c)
{
    if(isalpha(c))
    {
        if(c>='n')
            c-=13;
        else if(c>='a')
            c+=13;
        else if(c>='N')
            c-=13;
        else
            c+13;
    }
    return c;
}

int main(int argc, char *argv[])
{
    int ifd, ofd, i, j, n, err, numop;
    struct stat sbuf;
    const struct aiocb *aiolist[NBUF];
    off_t off=0;

    if(argc!=3)
        err_quit("usage: rot13 infile outfile");
    if((ifd=open(argv[1], O_RDONLY))<0)
        err_sys("can't open %s",argv[1]);
    if((ofd=open(argv[2],O_RDWR|O_CREAT|O_TRUNC,FILE_MODE))<0)
        err_sys("can't creat %s", argv[2]);
    if(fstat(ifd, &sbuf)<0)
        err_sys("fstat failed");

    for(i=0;i=sbuf.st_size)
                            bufs[i].last=1;
                        bufs[i].aiocb.aio_nbytes=BSZ;
                        if(aio_read(&bufs[i].aiocb)<0)
                            err_sys("aio_read failed");
                        aiolist[i]=&bufs[i].aiocb;
                        numop++;
                    }
                    break;

                case READ_PENDING:
                    if((err=aio_error(&bufs[i].aiocb))==EINPROGRESS)
                        continue;
                    if(err!=0)
                    {
                        if(err==-1)
                            err_sys("aio_error failed");
                        else
                            err_exit(err, "read failed");
                    }

                    if((n=aio_return(&bufs[i].aiocb))<0)
                        err_sys("aio_return failed");
                    if(n!=BSZ&&!bufs[i].last)
                        err_quit("short read (%d/%d)", n, BSZ);
                    for(j=0;j=sbuf.st_size)
                break;
        }
        else
        {
            if(aio_suspend(aiolist, NBUF,NULL)<0)
                err_sys("aio_suspend failed");
        }
    }
    bufs[0].aiocb.aio_fildes=ofd;
    if(aio_fsync(O_SYNC, &bufs[0].aiocb)<0)
        err_sys("aio_fsync failed");
    return 0;
}

Translate a file using ROT-13 and asynchronous I/O

你可能感兴趣的:(Advanced,Programming,in,the,Unix,Environment)