What happens during an unlink(2)

Barry Shein bzs at bu-cs.UUCP
Sat May 24 02:37:39 AEST 1986


Why would the following not work? It just takes file names and zeros
out the named files. One could remove them later, you could write a
trivial shell file to do both.

	-Barry Shein, Boston University
-----
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>

/*
 * zf file...
 *
 * scribble zeros onto a file or files
 *
 * This program is UNIX specific in that you have to find out
 * if the underlying system reallocates and copies updated blocks
 * on the disk or re-writes in place (that is, if you are zeroing
 * the file for security reasons.)
 *
 * Barry Shein, Boston University
 */

/*
 * If PORTABLE not defined uses some UNIX assumptions. On a non-UNIX system
 * you will probably have to provide the call to stat for size of the file
 * and, either remove the check for file type or provide that also.
 * That is, the program is not necessarily portable but I pointed out
 * what you would need to fix to port it to your system.
 */
/* #define PORTABLE */

char *prog;
char buf[BUFSIZ]; /* Assumes externs are zeroed, otherwise zero buf in main */
main(argc,argv) int argc; char **argv;
{
  FILE *fp;
  struct stat stbuf;

  prog = *argv;

/* uncomment and maybe provide bzero() if needed */
/*
  bzero(buf,sizeof(buf));
 */

  if(argc < 2) {
    fprintf(stderr,"Usage: %s file[s]\n",prog);
    exit(1);
  }
  ++argv;
  --argc;

  for(; argc > 0; ++argv, --argc) {
    /* get size and file type */
    if(stat(*argv,&stbuf) < 0) {
      perror(*argv);
      continue;
    }
    /* open for update from beginning of file */
    if((fp = fopen(*argv,"r+")) == 0) {
      perror(*argv);
      continue;
    }

    /* only zero certain file types, customize as needed */
    /* UNIX specific probably */
    switch(stbuf.st_mode & S_IFMT) {

    case S_IFREG:
    case S_IFCHR:
    case S_IFBLK:
      break;

    default:
      fprintf(stderr,"%s/%s: must be regular or char or block special\n",
	      prog,*argv);
      continue;
    }
    /* end UNIX specific probably */

    zfile(fp,stbuf.st_size);
    fclose(fp);
  }
  exit(0);
}
/*
 * zfile - zero all bytes in a file
 */
#ifdef PORTABLE
zfile(fp,size) FILE *fp; off_t size;
{
  while(size > 0) {
    fwrite(buf,sizeof(buf[0]),BUFSIZ > size ? size : BUFSIZ,fp);
    size -= BUFSIZ;
  }
}
#else
/*
 * This version of zfile will be faster on UNIX systems
 */
zfile(fp,size) FILE *fp; off_t size;
{
  while(size > 0) {
    write(fileno(fp),buf,BUFSIZ > size ? size : BUFSIZ);
    size -= BUFSIZ;
  }
}
#endif



More information about the Comp.sources.bugs mailing list