cc charfile.c
λ walter [learning-c/effective-c/ch8] → ./a.out
file position after write: 27
file position after write: 54
λ walter [learning-c/effective-c/ch8] → cat fred.txt
abcdefghijklmnopqrstuvwxyz
abcdefghijklmnopqrstuvwxyz
λ walter [learning-c/effective-c/ch8] → wc fred.txt
2 2 54 fred.txt
#include <stdio.h>
#include <stdlib.h>
int main(void) {
FILE *fp = fopen("fred.txt", "w+");
if (fp == NULL) {
fputs("unable to open file fred.txt\n", stderr);
return EXIT_FAILURE;
}
fpos_t pos; // to store the file position (ofset)
if (fgetpos(fp, &pos) != 0) {
perror("get position"); // perror() produces a message on stderr
// describing the last error encountered during
// a call to a system or lib function
//
// the argument string s is printed, followed by
// a colon and a blank. Then an error message
// corresponding to the current value of errno and
// new-line.
return EXIT_FAILURE;
}
if (fputs("abcdefghijklmnopqrstuvwxyz\n", fp) == EOF) {
fputs("cannot write to fred.txt file\n", stderr);
}
long int fpi = ftell(fp);
if (fpi == -1L) {
perror("seek");
return EXIT_FAILURE;
}
printf("file position after write: %ld\n", ftell(fp));
if (fputs("abcdefghijklmnopqrstuvwxyz\n", fp) == EOF) {
fputs("cannot write to fred.txt file\n", stderr);
}
fpi = ftell(fp);
if (fpi == -1L) {
perror("seek");
return EXIT_FAILURE;
}
printf("file position after write: %ld\n", ftell(fp));
// closing file
if (fclose(fp) == EOF) {
fputs("unable to close file\n", stderr);
}
return EXIT_SUCCESS;
}