1
0

strgen.c 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. /*
  2. * randomly select words from a dictionary
  3. *
  4. */
  5. #include <ctype.h>
  6. #include <time.h>
  7. #include <stdio.h>
  8. #include <string.h>
  9. #include <stdlib.h>
  10. #define LINE_LENGTH 80
  11. #define fileName "dictionary"
  12. int readDictionary(char * filename, char * * * dict)
  13. {
  14. FILE * fptr = fopen(filename, "r");
  15. if (fptr == NULL)
  16. {
  17. return 0;
  18. }
  19. /* count the lines */
  20. char oneWord[LINE_LENGTH];
  21. int wordCount = 0;
  22. char * * words;
  23. while (fgets(oneWord, LINE_LENGTH, fptr) != NULL)
  24. {
  25. if (strlen(oneWord) > 3)
  26. {
  27. wordCount ++;
  28. }
  29. }
  30. fseek(fptr, 0, SEEK_SET);
  31. words = malloc(sizeof(char *) * wordCount);
  32. int counter = 0;
  33. while (fgets(oneWord, LINE_LENGTH, fptr) != NULL)
  34. {
  35. if (strlen(oneWord) > 3)
  36. {
  37. int length = strlen(oneWord) + 1;
  38. words[counter] = malloc(sizeof(char) * length);
  39. strcpy(words[counter], oneWord);
  40. /* make first letter uppercase because sort in Linux is case
  41. insensitive */
  42. if (islower(oneWord[0]))
  43. {
  44. words[counter][0] = oneWord[0] - 'a' + 'A';
  45. }
  46. counter ++;
  47. }
  48. }
  49. fclose (fptr);
  50. * dict = words;
  51. return wordCount;
  52. }
  53. int main(int argc, char ** argv)
  54. {
  55. srand(time(NULL));
  56. if (argc < 2)
  57. {
  58. printf("how many words?\n");
  59. return EXIT_FAILURE;
  60. }
  61. int num = (int) strtol(argv[1], NULL, 10);
  62. char * * words;
  63. int numWords;
  64. numWords = readDictionary(fileName, & words);
  65. if (numWords == 0)
  66. {
  67. printf("cannot read dictionary\n");
  68. return EXIT_FAILURE;
  69. }
  70. int iter;
  71. for (iter = 0; iter < num; iter ++)
  72. {
  73. printf("%s", words[rand() % numWords]);
  74. }
  75. return EXIT_SUCCESS;
  76. }