#include #include #include #include #include void pfatal (char const *format, ...) { int errnum = errno; va_list args; fprintf (stderr, "%s: **** ", "tst"); va_start (args, format); vfprintf (stderr, format, args); va_end (args); fflush (stderr); /* perror bypasses stdio on some hosts. */ errno = errnum; perror (" "); fflush (stderr); exit(1); } /* Create FILE with OPEN_FLAGS, and with MODE adjusted so that we can read and write the file and that the file is not executable. Return the file descriptor. */ int create_file (char const *file, int open_flags, mode_t mode) { int fd; mode |= S_IRUSR | S_IWUSR; mode &= ~ (S_IXUSR | S_IXGRP | S_IXOTH); if (! (O_CREAT && O_TRUNC)) close (creat (file, mode)); fd = open (file, O_CREAT | O_TRUNC | open_flags, mode); if (fd < 0) pfatal ("Can't create file %s", file); return fd; } #define HAVE_FSEEKO 1 #ifdef HAVE_FSEEKO # define file_seek fseeko typedef off_t file_offset; #else # define file_seek fseek typedef long file_offset; #endif int main (int argc, char **argv) { FILE *pfp; pfp = fdopen(create_file ("tst.file", O_RDWR | O_BINARY, (mode_t) 0), "w+b"); if (!pfp) { pfatal("fopen"); } char* buf = "this is a test file\npretty cool, huh?\n"; size_t bufsize = sizeof(char) * strlen(buf); if (fwrite(buf, 1, bufsize, pfp) != bufsize) { pfatal("fwrite"); } if (fflush(pfp) != 0) { pfatal("pfp"); } if (file_seek(pfp, (file_offset) 0, SEEK_SET) != 0) { pfatal("file_seek"); } buf = (char*) malloc(bufsize); while (fread(buf, 1, bufsize, pfp) != 0) ; printf("buf\n---------\n%s", buf); exit(0); }