#include /** open fstat **/ #include /** open fstat **/ #include /** open **/ #include /** write close fstat **/ #include /** fprintf perror **/ #include /** EXIT_FAILURE EXIT_SUCCESS **/ #define TESTFILE "./tstfile" #define LOOPMAX 0xF void chklseek_then_read_byte(int fd, off_t pos); ssize_t chkwrite(int fd, const void *buf, size_t count); int main(int argc, char **argv) { int fd; unsigned char buf; if ((fd = open(TESTFILE, O_RDWR | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR)) == -1) { perror("main:: open failed"); return EXIT_FAILURE; } for (buf = 0; buf < LOOPMAX; buf++) chkwrite(fd, &buf, 1); if (close(fd) == -1) { perror("main:: close failed"); return EXIT_FAILURE; } return EXIT_SUCCESS; } ssize_t chkwrite(int fd, const void *buf, size_t count) { ssize_t count_ret, delta; off_t init_pos, final_pos = -1; struct stat stat; if ((init_pos = lseek(fd, 0, SEEK_CUR)) == -1) perror("chkwrite:: lseek failed"); if ((count_ret = write(fd, buf, count)) == -1) { perror("chkwrite:: write failed"); return count_ret; } if ((final_pos = lseek(fd, 0, SEEK_CUR)) == -1) perror("chkwrite:: lseek failed"); if (init_pos != -1 && final_pos != -1 && (delta = final_pos - init_pos) != count) { fprintf(stderr, "chkwrite:: %s bytes written " "(according to lseek)\n" "\tsupposed to be : %d byte(s)\n" "\tactual : %d byte(s)\n", (delta > count) ? "extra" : "too few", count, delta); fprintf(stderr, "\tfile pos (pre-wr ): %d\n", (int)init_pos); fprintf(stderr, "\tfile pos (post-wr ): %d\n", (int)final_pos); if (fstat(fd, &stat) == -1) perror("chkwrite:: fstat failed"); else fprintf(stderr, "\tfile size (fstat) : %d\n", (int)stat.st_size); } return count_ret; }