/* FILE.C */
#include <dos.h>
#include <conio.h>
#include <fcntl.h>
#include <share.h>

char file_prompt[] = "File? ";
char cant_open[] = "Can't open file\r\n";
char error_reading[] = "Error reading file\r\n";
char insuff_mem[] = "Insufficient memory; Press any key...\r\n";
char crlf[] = "\r\n";

#define PUTSTR(s)   \
    _dos_write(STDERR, (char far *) s, sizeof(s)-1, &wcount)

#define MIN_PARAS   4
#define WANT_PARAS  64
#define BYTES       (paras << 4)

#define STDERR      2

#ifdef TSR
application(void)
#else
main(void)
#endif
{
    char buf[81];
    char far *s;
    unsigned rcount, wcount, ret, paras, seg;
    int f;
    
    /* prompt for filename */
    if (PUTSTR(file_prompt) != 0)
        return;

    /* get filename */
    if ((_dos_read(STDERR, buf, 80, &rcount) != 0) || (rcount < 3))
        return;
    /* replace CRLF with NULL */
    buf[rcount-2] = '\0';
    
    /* try to allocate: first try a lot, then a little */
    if (_dos_allocmem(WANT_PARAS, &seg) == 0)
        paras = WANT_PARAS;
    else if (_dos_allocmem(MIN_PARAS, &seg) == 0)
        paras = MIN_PARAS;
    else
    {
        PUTSTR(insuff_mem);
        return;
    }
    FP_SEG(s) = seg;
    FP_OFF(s) = 0;
    
    /* open file */
    if (_dos_open(buf, O_RDWR | SH_DENYNO, &f) != 0)
        return PUTSTR(cant_open);
    
    /* display file */
    while (((ret = _dos_read(f, s, BYTES, &rcount)) == 0) && rcount)
        if (_dos_write(STDERR, s, rcount, &wcount) != 0)
            break;
    /* write one more CRLF */
    PUTSTR(crlf);
    if (ret)
        PUTSTR(error_reading);
    
    /* free memory */
    _dos_freemem(seg);
    
    /* close file */
    _dos_close(f);
    
    PUTSTR("Press any key...");
}
