#include /* for open, lseek */ #include /* for open */ #include /* for open */ #include /* for fprintf etc */ #include /* for exit */ #include /* for open, lseek */ #include "mem.h" int init_shared_file(int *fd, char *file, size_t size){ *fd = open(file, O_RDWR | O_CREAT | O_EXCL, S_IRWXU); if(*fd < 0){ fprintf(stderr, "The file: %s exists -- opening it and checking size\n", file); return open_shared_file(fd, file, size); } else { fprintf(stderr, "The file: %s doesn't exist -- creating it\n", file); if(lseek(*fd, size - 1, SEEK_SET) == -1){ perror("lseek error!"); return -1; } if(write(*fd, "", 1) != 1){ perror("write error!"); return -1; } } return 0; } int open_shared_file(int *fd, char *file, size_t size){ struct stat statbuf; *fd = open(file, O_RDWR, S_IRWXU); if(*fd < 0){ fprintf(stderr, "Couldn't open %s! Exiting\n", file); return -1; } if(fstat(*fd, &statbuf) < 0){ perror("fstat error!"); return -1; } fprintf(stderr, "Checking file size: %s is %ld bytes\n", file, statbuf.st_size); if(statbuf.st_size < size){ if(lseek(*fd, size - 1, SEEK_SET) == -1){ perror("lseek error!"); return -1; } if(write(*fd, "", 1) != 1){ perror("write error!"); return -1; } } if(fstat(*fd, &statbuf) < 0){ perror("fstat error!"); return -1; } fprintf(stderr, "The file: %s is now %ld bytes\n", file, statbuf.st_size); return 0; }