gd.c 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <getopt.h>
  5. #include <stdint.h>
  6. struct Options {
  7. const char *output;
  8. unsigned count;
  9. } opts;
  10. static void
  11. usage (void)
  12. {
  13. printf ("Usage: gd [OPTION]\n"
  14. "Options:\n"
  15. " -h, --help Show this help message and exit\n"
  16. " -o, --output Output filename\n"
  17. " -c, --count Number of blocks\n");
  18. }
  19. static void
  20. parse_options (int argc, char *const *argv)
  21. {
  22. enum {
  23. OPT_HELP = 'h',
  24. OPT_OUTPUT = 'o',
  25. OPT_COUNT = 'c',
  26. };
  27. static struct option long_options[] = {
  28. { "help", no_argument, 0, OPT_HELP },
  29. { "output", required_argument, 0, OPT_OUTPUT },
  30. { "count", required_argument, 0, OPT_COUNT },
  31. { 0, 0, 0, 0 },
  32. };
  33. int ret;
  34. int index;
  35. if (argc == 1) {
  36. usage ();
  37. exit (0);
  38. }
  39. memset (&opts, 0, sizeof (struct Options));
  40. while ((ret = getopt_long (argc, argv, "o:c:h", long_options, &index)) != -1) {
  41. switch (ret) {
  42. case OPT_HELP:
  43. usage ();
  44. exit (0);
  45. case OPT_OUTPUT:
  46. opts.output = optarg;
  47. break;
  48. case OPT_COUNT:
  49. opts.count = (size_t) atol (optarg);
  50. break;
  51. default:
  52. break;
  53. }
  54. }
  55. }
  56. static void
  57. write_data (void)
  58. {
  59. FILE *fp;
  60. uint32_t i;
  61. fp = opts.output != NULL ? fopen (opts.output, "wb") : stdout;
  62. for (i = 0; i < opts.count; i++) {
  63. fwrite (&i, 4, 1, fp);
  64. }
  65. if (opts.output != NULL)
  66. fclose (fp);
  67. }
  68. int
  69. main (int argc, char const* argv[])
  70. {
  71. parse_options (argc, (char *const *) argv);
  72. write_data ();
  73. return 0;
  74. }