you have to reopen file after count
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define WIDTH 50
int main(int argc, const char **argv)
{
char **wordarr, **wordpc,ch ;
// Commented out because they are not being used at all
// int option=1, library, howmany, i,number, numwords=0,count=4;
// re declared what you are using in your program here
int i,number, numwords=0,count=4;
//open the file
// made it easier to just name a file / anyfile
// on the command line to read it instead
// it is just easier for me
// so I can use whatever file I want
// you do not have to do that.
char *filename = strdup(argv[1]);
FILE *fp;
fp = fopen(filename, "r");
if (fp == NULL) {
fprintf(stderr, "File not found\n");
exit(1);
}
// get your count you want
//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];
char *tok;
i=0;
// re open file so I can read it from
// the start again.
// don't know if that is entirely legal
// I'd have to look into it further. but it works.
fp = fopen(filename, "r");
// to get it to read entire file
// put it in a loop
while ( fgets(buffer, 10000, fp) != NULL)
{
tok = strtok(buffer, " . , !");
while (tok != NULL)
{
//strcpy(wordarr[(i)++], tok);
// I just put the tok into the element
// do it how ever you wish. both work.
wordarr[i++] = tok;
tok = strtok(NULL, " . , !");
}
} // end outter loop
fclose(fp);
// use your i from the while loop
// for lenght used in the array
// so you'll just print out
// what was put in.
// just make a new count var
for (int j = 0; j < i; j++)
{
printf("[%s]\n", wordarr[j]);
}
// this is just crazy code to me so far. :D
// how is scanf reading anything?
// it is coming up zero
printf("\nWrite how many letters does the word have? y/n\n");
scanf("%d", &number);
printf("%d number\n", number);
int len,*temp= NULL, *tempi= NULL;
//goes to the first array and searches for words with NUM characters
//stores the words to an array
for(i=0; i<count; i++){
len = strlen(wordarr[i]);
printf("length %d\n", len);
if(strlen(wordarr[i]) == number){
// long unsinged int lu
printf("%lu\n", strlen(wordarr[i]));
numwords++;
temp = (int*) realloc(tempi, numwords *sizeof(int));
if(temp != NULL){
tempi=temp;
tempi[numwords-1]= i;
}
}
}
//
wordpc = (char**)malloc(sizeof(char*) * numwords);
for(i = 0; i<numwords; i++){
wordpc[i] = (char*)malloc(sizeof(char) * WIDTH);
}
//
/*for(i=0; i<howmany; i++){
if(strlen(wordarr[i]) == number){
wordarr[tempi] = wordpc[i];
}
}*/
//loop not needed
//Deallocate the memory
/*
for (i=0; i<count; i++) {
free(wordarr[i]);
free(wordpc[i]);
}
*/
// just this
free(wordarr);
free(wordpc);
// me freeing my strdup
free(filename);
return 0;
}