Guest User

Untitled

a guest
Dec 17th, 2017
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.63 KB | None | 0 0
  1. int main(int argc, char *argv[]) {
  2. // read file
  3. char *content = NULL;
  4. if (argc != 2 || !(content = get_file_contents(argv[1])))
  5. exit(EXIT_FAILURE);
  6.  
  7. // find the number of words
  8. unsigned long words_count = 0;
  9. bool inword = false;
  10. for (char *s = content; *s; ++s) {
  11. if (isalpha(*s)) { // C locale: upper, lower letter
  12. if (!inword) { // new word
  13. inword = !inword;
  14. ++words_count;
  15. }
  16. }
  17. else if (inword) {
  18. inword = !inword; // end of word
  19. }
  20. }
  21.  
  22. // put words into array
  23. char* *words;
  24. if (words_count > (SIZE_MAX / sizeof *words)
  25. || !(words = (char**)malloc(words_count * sizeof *words)))
  26. exit(EXIT_FAILURE); // let OS cleanup memory
  27.  
  28. char *s = content; // rewind
  29. for (unsigned long i = 0; i < words_count; ++i) {
  30. for ( ; !isalpha(*s); ++s); // find start of the word
  31. words[i] = s;
  32. for ( ; isalpha(*s); ++s); // find end of the word
  33. *s = '';
  34. }
  35. // print words
  36. for (unsigned long i = 0; i < words_count; ++i) puts(words[i]);
  37. }
  38.  
  39. /// read file into null-terminated C-string
  40. char* get_file_contents(const char* filename) {
  41. FILE *fp = NULL;
  42. unsigned long size;
  43. char *buf = NULL;
  44.  
  45. if((fp = fopen(filename, "rb"))
  46. && !fseek(fp, 0, SEEK_END)
  47. && (size = ftell(fp)) != (unsigned long)EOF // find file size
  48. && size < LONG_MAX && size < SIZE_MAX
  49. && (buf = (char*)malloc(size + 1)) // allocate memory for the content
  50. && (rewind(fp), 1)
  51. && fread(buf, sizeof *buf, size, fp) == size // read the content
  52. && !fclose(fp)) {
  53. buf[size] = '';
  54. return buf;
  55. }
  56.  
  57. // error
  58. if (fp) fclose(fp);
  59. free(buf);
  60. return NULL;
  61. }
Add Comment
Please, Sign In to add comment