Advertisement
Guest User

Untitled

a guest
Dec 2nd, 2016
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.71 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5. const int STEPSIZE = 100;
  6.  
  7. char **loadfile(char *filename, int *len);
  8.  
  9. int main(int argc, char *argv[])
  10. {
  11. if(argc == 1)
  12. {
  13. fprintf(stderr, "Must supply a file name to read.\n");
  14. exit(1);
  15. }
  16. int i;
  17. int len = 0;
  18. char **words = loadfile(argv[1], &len);
  19.  
  20. //display 1st 100 lines.
  21. printf("%d\n", len);
  22. for(i = 0; i < len; i++)
  23. {
  24. printf("%s\n", words[i]);
  25. }
  26. printf("Done\n");
  27.  
  28. return (EXIT_SUCCESS);
  29. }
  30.  
  31. char **loadfile(char *filename, int *len)
  32. {
  33. FILE *fp = fopen(filename, "r");
  34. if(!fp)
  35. {
  36. fprintf(stderr, "Can't open %s for reading.\n", filename);
  37. return NULL;
  38. }
  39.  
  40. int arrlen = STEPSIZE;
  41.  
  42. //Allocate space for 100 char pointers.
  43. char **lines = (char**)malloc(arrlen*sizeof(char*));
  44.  
  45. char buff[10000];
  46. int i = 0;
  47.  
  48. while(fgets(buff, 10000, fp))
  49. {
  50. //Check for full array, if so, extend the array
  51. if(i = arrlen)
  52. {
  53. arrlen += STEPSIZE;
  54. char **newlines = realloc(lines, arrlen*sizeof(char*));
  55. if(!newlines)
  56. {
  57. fprintf(stderr, "Can't reallocate\n");
  58. exit(1);
  59. }
  60. lines = newlines;
  61. }
  62. // trim off \0 at the end
  63. buff[strlen(buff)-1] = '\0';
  64. //get length of buffer
  65. int blen = strlen(buff);
  66.  
  67. char *str = (char*)malloc((blen+1)*sizeof(char));
  68.  
  69. //copy string from buff to structure
  70. strcpy(str, buff);
  71.  
  72. lines[i] = str;
  73.  
  74. i++;
  75. }
  76.  
  77. *len = i; //Set length of char pointers
  78. return lines;
  79. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement