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

Appfs Exercise 1: stream input. More...

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

Go to the source code of this file.

Macros

#define MAX_NUMS   ((INT_MAX >> 5) + 1)
 Maximum number of 32 bit ints we need to store bits. More...
 

Functions

int main (int argc, char **argv)
 Program to read a file with binary positive 32 bit integers, sort the numbers and print them sorted. More...
 

Detailed Description

Author
Thorsten Koch
Date
18Oct2014

gcc -O3 -Wall -std=c99 -o ex1b ex1b.c

Use stream file for input

Definition in file ex1b.c.

Macro Definition Documentation

#define MAX_NUMS   ((INT_MAX >> 5) + 1)

Definition at line 16 of file ex1b.c.

Function Documentation

int main ( int  argc,
char **  argv 
)

Actually, the numbers are not sorted. There is an array with one bit for each possible number. Upon reading the respective bit is set for the number recognized. At the end the array is scanned in order and the numbers present are printed.

Parameters
argv[1] name of file to read

Definition at line 26 of file ex1b.c.

27 {
28  const char* usage = "usage: %s filename\n";
29 
30  /* made static, because otherwise, the stack size might be too small.
31  */
32  static unsigned int have_num[MAX_NUMS];
33 
34  FILE* fp;
35  int n;
36  int total_nums = 0;
37 
38  /* we assume 32 bit integers, otherwise it will not work
39  */
40  assert(sizeof(int) == 4);
41 
42  /* Check arguments, we need a filename.
43  */
44  if (argc < 2)
45  {
46  fprintf(stderr, usage, argv[0]);
47  exit(EXIT_FAILURE);
48  }
49 
50  memset(have_num, 0, sizeof(have_num)); // Proably uneccessary
51 
52  /* Open file
53  */
54  if (NULL == (fp = fopen(argv[1], "r")))
55  {
56  perror(argv[1]);
57  exit(EXIT_FAILURE);
58  }
59 
60  /* Read from file until data exhausted
61  */
62  while(fread(&n, sizeof(n), 1, fp))
63  {
64  total_nums++;
65 
66  /* Check input: really >= 0 ? Otherwise ignore
67  */
68  if (n >= 0)
69  {
70  int idx = n >> 5; // n / 32
71  unsigned int msk = 1 << (n & 31); // bit number n mod 32
72 
73  assert(idx >= 0 && idx < MAX_NUMS);
74 
75  have_num[idx] |= msk;
76  }
77  }
78  if (fclose(fp))
79  {
80  perror("fclose: ");
81  exit(EXIT_FAILURE);
82  }
83 
84  fprintf(stderr, "Total numbers read = %d\n", total_nums);
85 
86  for(int i = 0; i < MAX_NUMS; i++)
87  if (have_num[i]) // just for speed up
88  for(int k = 0; k < 31; k++)
89  if (have_num[i] & (1 << k))
90  printf("%d\n", (i << 5) + k);
91 
92  return EXIT_SUCCESS;
93 }
#define MAX_NUMS
Maximum number of 32 bit ints we need to store bits.
Definition: ex1b.c:16