1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define WIDTH 50
int main()
{
/**/
char **wordarr, *wordpc,ch ;
int option=1, library, howmany, i,number, numwords=0,count=0;
//open the file
FILE *fp;
fp = fopen("file.txt", "r");
if (fp == NULL) {
fprintf(stderr, "File not found\n");
exit(1);
}
//counts the words in the file
while((ch = fgetc(fp)) != EOF){
if(ch == ' ' || ch == '\n' || ch == ',' || ch == '.'){
count++;
}
}
//making the array
wordarr = (char**)malloc(sizeof(char*) * count);
for(i = 0; i<count; i++){
wordarr[i] = (char*)malloc(sizeof(char) * WIDTH);
}
//
//putting the words into the array
char buffer[10000];
fgets(buffer, 10000, fp);
char *tok;
i=0;
tok = strtok(buffer, " .,!");
while (tok != NULL) {
/*if (i >= howmany) {
howmany *= 2;
wordarr = (char**)realloc(wordarr, sizeof(char*) * howmany);
for (i=howmany/2; i<howmany; i++) {
wordarr[i] = (char*)malloc(sizeof(char) * WIDTH);
}
printf("realloc\n");
}*/
strcpy(wordarr[(i)++], tok);
tok = strtok(NULL, " .,!");
}
fclose(fp);
for (i=0; i<count; i++) {
printf("[%s]\n", wordarr[i]);
}
//
for (i=0; i<count; i++) {
free(wordarr[i]);
}
free(wordarr);
}
|