APPFS
Advanced practical programming for scientists
 All Data Structures Files Functions Variables Typedefs Macros
ex1b.c
Go to the documentation of this file.
1 
10 #include <stdio.h>
11 #include <stdlib.h>
12 #include <limits.h>
13 #include <string.h>
14 #include <assert.h>
15 
16 #define MAX_NUMS ((INT_MAX >> 5) + 1)
17 
18 
26 int main(int argc, char** argv)
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 }
int main(int argc, char **argv)
Program to read a file with binary positive 32 bit integers, sort the numbers and print them sorted...
Definition: ex1b.c:26
#define MAX_NUMS
Maximum number of 32 bit ints we need to store bits.
Definition: ex1b.c:16