#include /* C example */ #include #include /* for errno */ #include /* for strerror */ int main(int argc, char **argv) { FILE *fp; long position; char buffer[256]; fp = fopen("file", "w+"); if (fp == NULL) { fprintf(stderr, "can't open file: %s\n", strerror(errno)); return EXIT_FAILURE; } fprintf(fp, "hello\n"); if (fflush(fp) != 0) { fprintf(stderr, "can't fflush: %s\n", strerror(errno)); return EXIT_FAILURE; } position = ftell(fp); if (position == -1) { fprintf(stderr, "can't ftell: %s.\n", strerror(errno)); return EXIT_FAILURE; } printf("position %ld\n", position); if (fseek(fp, 0, SEEK_SET) != 0) { /* rewind file back to beginning */ fprintf(stderr, "can't fseek: %s.\n", strerror(errno)); return EXIT_FAILURE; } position = ftell(fp); if (position == -1) { fprintf(stderr, "can't ftell: %s.\n", strerror(errno)); return EXIT_FAILURE; } printf("position %ld\n", position); if (fscanf(fp, "%s", buffer) != 1) { fprintf(stderr, "can't fscanf\n"); if (ferror(fp)) { fprintf(stderr, ": %s", strerror(errno)); } fprintf(stderr, ".\n"); } printf("%s\n", buffer); if (fclose(fp) != 0) { fprintf(stderr, "can't fclose: %s.\n", strerror(errno)); return EXIT_FAILURE; } return EXIT_SUCCESS; }