APPFS
Advanced practical programming for scientists
 All Data Structures Files Functions Variables Typedefs Enumerations Enumerator Macros
ex4_readline.c
Go to the documentation of this file.
1 
10 #include <stdio.h> // fopen
11 #include <stdlib.h> // EXIT_*
12 #include <string.h> // strpbrk
13 #include <assert.h> // assert
14 #include <ctype.h> // isspace
15 
16 #define MAX_LINE_LEN 512 // Maximum input line length
17 
22 int process_file(const char* filename)
23 {
24  assert(NULL != filename);
25  assert(0 < strlen(filename));
26 
27  FILE* fp;
28  char buf[MAX_LINE_LEN];
29  char* s;
30  int lines = 0;
31 
32  if (NULL == (fp = fopen(filename, "r")))
33  {
34  fprintf(stderr, "Can't open file %s\n", filename);
35  return -1;
36  }
37  while(NULL != (s = fgets(buf, sizeof(buf), fp)))
38  {
39  char* t = strpbrk(s, "#\n\r");
40 
41  lines++;
42 
43  if (NULL != t) /* else line is not terminated or too long */
44  *t = '\0'; /* clip comment or newline */
45 
46  /* Skip over leading space
47  */
48  while(isspace(*s))
49  s++;
50 
51  /* Skip over empty lines
52  */
53  if (!*s) /* <=> (*s == '\0') */
54  continue;
55 
56  /* do processing here
57  */
58  }
59  fclose(fp);
60 
61  return lines;
62 }
63 
64 int main(int argc, char** argv)
65 {
66  if (argc < 2 || strlen(argv[1]) <= 0)
67  {
68  fprintf(stderr, "usage: %s filename", argv[0]);
69  return EXIT_FAILURE;
70  }
71  printf("%d lines\n", process_file(argv[1]));
72 
73  return EXIT_SUCCESS;
74 }
#define MAX_LINE_LEN
Definition: ex4_readline.c:16
int process_file(const char *filename)
Read a textfile, remove comments and process lines.
Definition: ex4_readline.c:22
int main(int argc, char **argv)
Definition: ex4_readline.c:64