APPFS
Advanced practical programming for scientists
 All Data Structures Files Functions Variables Typedefs Enumerations Enumerator Macros
Macros | Functions
ex4_readline.c File Reference

Appfs Example: line wise text input. More...

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

Go to the source code of this file.

Macros

#define MAX_LINE_LEN   512
 

Functions

int process_file (const char *filename)
 Read a textfile, remove comments and process lines. More...
 
int main (int argc, char **argv)
 

Detailed Description

Author
Thorsten Koch
Date
07Nov2014

gcc -O2 -Wall -o ex4_readline ex4_readline.c

Using fgets() for input

Definition in file ex4_readline.c.

Macro Definition Documentation

#define MAX_LINE_LEN   512

Definition at line 16 of file ex4_readline.c.

Function Documentation

int main ( int  argc,
char **  argv 
)

Definition at line 64 of file ex4_readline.c.

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 }
int process_file(const char *filename)
Read a textfile, remove comments and process lines.
Definition: ex4_readline.c:22
int process_file ( const char *  filename)
Parameters
filenamename of file to read
Returns
number of lines read

Definition at line 22 of file ex4_readline.c.

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 }
#define MAX_LINE_LEN
Definition: ex4_readline.c:16