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

Appfs Exercise 1: stream input from stdin. 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 (void)
 Program to read binary positive 32 bit integers from stdin, sort the numbers and print them sorted. More...
 

Detailed Description

Author
Thorsten Koch
Date
18Oct2014

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

Use stdin for input

Definition in file ex1b2.c.

Macro Definition Documentation

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

Definition at line 16 of file ex1b2.c.

Function Documentation

int main ( void  )

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.

Definition at line 25 of file ex1b2.c.

26 {
27  /* made static, because otherwise, the stack size might be too small.
28  */
29  static unsigned int have_num[MAX_NUMS];
30 
31  int n;
32  int total_nums = 0;
33 
34  /* we assume 32 bit integers, otherwise it will not work
35  */
36  assert(sizeof(int) == 4);
37 
38  memset(have_num, 0, sizeof(have_num)); // Proably uneccessary
39 
40  /* Read from file until data exhausted
41  */
42  while(fread(&n, sizeof(n), 1, stdin))
43  {
44  total_nums++;
45 
46  /* Check input: really >= 0 ? Otherwise ignore
47  */
48  if (n >= 0)
49  {
50  int idx = n >> 5; // n / 32
51  unsigned int msk = 1 << (n & 31); // bit number n mod 32
52 
53  assert(idx >= 0 && idx < MAX_NUMS);
54 
55  have_num[idx] |= msk;
56  }
57  }
58  if (!feof(stdin))
59  {
60  perror("fread: ");
61  exit(EXIT_FAILURE);
62  }
63 
64  fprintf(stderr, "Total numbers read = %d\n", total_nums);
65 
66  for(int i = 0; i < MAX_NUMS; i++)
67  if (have_num[i]) // just for speed up
68  for(int k = 0; k < 31; k++)
69  if (have_num[i] & (1 << k))
70  printf("%d\n", (i << 5) + k);
71 
72  return EXIT_SUCCESS;
73 }
#define MAX_NUMS
Maximum number of 32 bit ints we need to store bits.
Definition: ex1b2.c:16