Skip to content

Instantly share code, notes, and snippets.

@waltervargas
Created May 11, 2021 22:13
Show Gist options
  • Save waltervargas/03e9165a8075b498ca3fab4002465bee to your computer and use it in GitHub Desktop.
Save waltervargas/03e9165a8075b498ca3fab4002465bee to your computer and use it in GitHub Desktop.
reading char files in C

Reading char files in C

λ walter [learning-c/effective-c/ch8] → cat > signals.txt <<EOF   
heredoc> 1 HUP   Hangup
2 INT   Interrupt
3 QUIT  Quit
4 ILL   Illegal instruction
5 TRAP  Trace trap
6 ABRT  Abort
7 EMT   EMT trap
8 FPE   Floating-point exception
EOF
λ walter [learning-c/effective-c/ch8] → cc readchar.c
λ walter [learning-c/effective-c/ch8] → ./a.out     
signal
 number = 1
 name = HUP
 description = Hangup
signal
 number = 2
 name = INT
 description = Interrupt
signal
 number = 3
 name = QUIT
 description = Quit
signal
 number = 4
 name = ILL
 description = Illegal instruction
signal
 number = 5
 name = TRAP
 description = Trace trap
signal
 number = 6
 name = ABRT
 description = Abort
signal
 number = 7
 name = EMT
 description = EMT trap
signal
 number = 8
 name = FPE
 description = Floating-point exception

Code

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void) {
  int status = EXIT_SUCCESS;
  FILE *in;

  struct sigrecord {
    int signum;
    char signame[10];
    char sigdesc[100];
  } sigrec;

  if ((in = fopen("signals.txt", "r")) == NULL) {
    fputs("unable to open signals.txt\n", stderr);
    return EXIT_FAILURE;
  }

  do {
    int n = fscanf(in, "%d%9s%*[ \t]%99[^\n]", &sigrec.signum, sigrec.signame,
                   sigrec.sigdesc);
    if (n == 3) {
      printf("signal\n number = %d\n name = %s\n description = %s\n",
             sigrec.signum, sigrec.signame, sigrec.sigdesc);
    } else if (n != EOF) {
      fputs("failed to match signum, signame or sigdesc\n", stderr);
      status = EXIT_FAILURE;
      break;
    } else {
      break;
    }
  } while (1);

  if (fclose(in) == EOF) {
    fputs("failed to close file\n", stderr);
    status = EXIT_FAILURE;
  }
  return status;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment