/*
 * Floppy-disk buffer flush program.
 * Copyright (C) 1995 Bruce Perens
 * This program is free software under the GNU General Public License
 */
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <sys/ioctl.h>

/* Two ways to flush stuff. */
#define BLKFLSBUF  _IO(0x12,97) /* linux/fs.h */
#define FDFLUSH    _IO(2,0x4b)  /* linux/fd.h */

static const char	fd0[] = "/dev/fd0";

int
main(int argc, char * * argv)
{
	const char *	floppy = fd0;
	int		fd;
	int		res;

	if ( argc == 2 )
		floppy = argv[1];
	else if ( argc > 2 ) {
	    fprintf(stderr, "usage: fdflush [device]\n");
	    return 3;
	}

	/* Try to open read/write first */
	fd = open(floppy, O_RDWR);
	if (fd < 0)
		fd = open(floppy, O_RDONLY);

	if ( fd < 0 ) {
		fprintf(stderr, "%s: %s.\n", floppy, strerror(errno));
		return 2;
	}

	/* Only report an error if both ioctl calls fail. */
	res = ioctl(fd, FDFLUSH, 0);
	if ( ioctl(fd, BLKFLSBUF, 0) != 0 && res != 0) {
		fprintf(stderr, "%s: fdflush: %s.\n", floppy, strerror(errno));
		close(fd);
		return 1;
	}

	close(fd);

	return 0;
}
