Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- const int STEPSIZE = 100;
- char **loadfile(char *filename, int *len);
- int main(int argc, char *argv[])
- {
- if(argc == 1)
- {
- fprintf(stderr, "Must supply a file name to read.\n");
- exit(1);
- }
- int i;
- int len = 0;
- char **words = loadfile(argv[1], &len);
- //display 1st 100 lines.
- printf("%d\n", len);
- for(i = 0; i < len; i++)
- {
- printf("%s\n", words[i]);
- }
- printf("Done\n");
- return (EXIT_SUCCESS);
- }
- char **loadfile(char *filename, int *len)
- {
- FILE *fp = fopen(filename, "r");
- if(!fp)
- {
- fprintf(stderr, "Can't open %s for reading.\n", filename);
- return NULL;
- }
- int arrlen = STEPSIZE;
- //Allocate space for 100 char pointers.
- char **lines = (char**)malloc(arrlen*sizeof(char*));
- char buff[10000];
- int i = 0;
- while(fgets(buff, 10000, fp))
- {
- //Check for full array, if so, extend the array
- if(i = arrlen)
- {
- arrlen += STEPSIZE;
- char **newlines = realloc(lines, arrlen*sizeof(char*));
- if(!newlines)
- {
- fprintf(stderr, "Can't reallocate\n");
- exit(1);
- }
- lines = newlines;
- }
- // trim off \0 at the end
- buff[strlen(buff)-1] = '\0';
- //get length of buffer
- int blen = strlen(buff);
- char *str = (char*)malloc((blen+1)*sizeof(char));
- //copy string from buff to structure
- strcpy(str, buff);
- lines[i] = str;
- i++;
- }
- *len = i; //Set length of char pointers
- return lines;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement