Skip to content

Instantly share code, notes, and snippets.

@waltervargas
Last active May 13, 2021 13:00
Show Gist options
  • Save waltervargas/299dd4ddbfea3f44dc1b05f1c46f8cd4 to your computer and use it in GitHub Desktop.
Save waltervargas/299dd4ddbfea3f44dc1b05f1c46f8cd4 to your computer and use it in GitHub Desktop.
writing char files in C

Writing char files in C

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

Code

#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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment