#include /* for error messages */ #include /* for exit() */ #include #include #include #include #include /* Sample code for creating a file with holes. * Author: Mark A. Sheldon, (c) 15 March 2007 * * Usage: seeky filename string1 len1 offset string2 len2 * opens filename for writing. The file must NOT exist, and will be * created. * len1 bytes are written starting with string1 at the start of the * file. * Then seeks to position offset in file and writes len2 bytes * starting with string2. */ char *usage_fmt = "Usage: %s filename string1 len1 offset string2 len2\n"; int main (int argc, char **argv) { int fd, rtn; int len1 = 0, offset = 0, len2 = 0; char *prog_name = argv[0], *string1, *string2; if ((argc != 4) && ((sscanf(argv[3], "%d", &len1) != 1) || (sscanf(argv[4], "%d", &offset) != 1) || (sscanf(argv[6], "%d", &len2) != 1))) { fprintf(stderr, usage_fmt, prog_name); exit(EINVAL); } string1 = argv[2]; string2 = argv[5]; fd = open(argv[1], (O_WRONLY | O_CREAT | O_EXCL), (S_IRUSR | S_IWUSR)); if (fd == -1) { perror("Cannot open file"); exit(errno); } /* Note: not checking for short writes. For lab it's ok. */ if ((rtn = write(fd, string1, len1)) == -1) { perror("Cannot write file"); exit(errno); } if ((rtn = lseek(fd, offset, SEEK_CUR)) == (off_t) -1) { perror("Cannot seek"); exit(errno); } /* Note: not checking for short writes. For lab it's ok. */ if ((rtn = write(fd, string2, len2)) == -1) { perror("Cannot write file"); exit(errno); } if ((rtn = close(fd) == -1)) { perror("Cannot close file"); exit(errno); } return 0; }