Its working fine.
#ifdef __USAGE
%C - Create contiguous file
%C <size
#endif
#include <env.h
#include <errno.h
#include <fcntl.h
#include <limits.h
#include <stdarg.h
#include <stdio.h
#include <stdlib.h
#include <string.h
#include <sys/disk.h
#include <sys/fsys.h
#include <sys/stat.h
#include <unistd.h
#define MAX_ATTEMPTS 128
int trygrow(int blkdev, int fd, int nblks)
{
struct _fsys_stat st;
struct _xblk xblk;
long blkno;
if (lseek(fd, nblks * _BLOCK_SIZE - 1, SEEK_SET) == -1)
return(errno);
if (write(fd, “”, 1) != 1)
return(errno);
if (fsys_fstat(fd, &st) == -1)
return(errno);
if (st.st_num_xtnts == 1)
return(EOK);
for (blkno = st.st_xblk; block_read(blkdev, blkno, 1, &xblk) == 1 &&
xblk.xblk_next_xblk != 0; blkno = xblk.xblk_next_xblk)
;
if (ltrunc(fd, -xblk.xblk_xtnts[xblk.xblk_num_xtnts - 1].xtnt_size *
_BLOCK_SIZE, SEEK_END) == -1)
return(errno);
return(-1);
}
static void fatal(const char *prog, const char *errmsg, …)
{
va_list args;
fprintf(stderr, "%s: ", prog);
va_start(args, errmsg);
vfprintf(stderr, errmsg, args);
va_end(args);
fprintf(stderr, “\n”);
exit(EXIT_FAILURE);
}
int main(int argc, char *argv[])
{
char *filename, *tmpfilename, *cp;
int nblks, bytes, result, i, j;
int blkdev, fd[MAX_ATTEMPTS];
char device[PATH_MAX + 1], tmp[L_tmpnam + 1];
if (argc != 3)
fatal(argv[0], "specify and ");
filename = argv[1];
bytes = strtol(argv[2], &cp, 0);
if (*cp == ‘b’ || *cp == ‘B’)
bytes *= _BLOCK_SIZE, ++cp;
else if (*cp == ‘k’ || *cp == ‘K’)
bytes <<= 10, ++cp;
else if (*cp == ‘m’ || *cp == ‘M’)
bytes <<= 20, ++cp;
if (!bytes || *cp != ‘\0’)
fatal(argv[0], “invalid specification”);
nblks = (bytes - 1) / _BLOCK_SIZE + 1;
if ((cp = strrchr(filename, ‘/’)) != NULL) {
*cp = ‘\0’;
setenv(“TMPDIR”, filename, !0);
if (fsys_get_mount_dev(filename, device) == -1)
fatal(argv[0], “unable to determine underlying device - %s”,
strerror(errno));
*cp = ‘/’;
}
else {
setenv(“TMPDIR”, “.”, !0);
device[0] = ‘.’, device[1] = ‘\0’;
}
if ((blkdev = open(device, O_RDONLY)) == -1)
fatal(argv[0], “unable to open underlying device - %s”, strerror(errno));
result = -1;
for (i = 0; i < MAX_ATTEMPTS; ++i) {
tmpfilename = tmpnam(tmp);
if ((fd > = open(tmpfilename, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR |
S_IWUSR | S_IRGRP | S_IROTH)) == -1)
fatal(argv[0], “unable to create working file - %s”, strerror(errno));
if ((result = trygrow(blkdev, fd> , nblks)) == EOK) {
if (rename(tmpfilename, filename) != -1)
break;
result = errno;
}
unlink(tmpfilename);
if (result != -1)
fatal(argv[0], “unable to grow working file - %s”, strerror(result));
}
for (j = 0; j <= i; ++j)
close(fd[j]);
close(blkdev);
if (result)
fatal(argv[0], “unable to create contiguous file - disk too fragmented”);
return(EXIT_SUCCESS);
}