I suspect your problem is the use of sizeof. Using sizeof on an array produces different results to using sizeof on a char pointer.
Code:
char string2[100];
char * string = calloc(100, 1);;
printf("sizeof(string) = %d", sizeof(string)); /* prints sizeof(char *), probably 4 */
printf("sizeof(string2) = %d", sizeof(string2)); /* prints 100 */
Therefore when dynamically allocating your memory you need to keep the size of the buffer in a variable and use that instead of sizeof.
Code:
int countwords (char *location)
{
/*The aim of this function is as titled, to count the number of words from a text file*/
int countwords=0,count=0;
char *currentword;
char * string;
size_t string_size;
FILE *text,*text2;
text=fopen(location,"r");//location has been given outside this function to where the text file exists.
text2=fopen(".\\textfiles\\temp.txt","w");//using a file because I cnanot find a way of strtok can to delimit a newlines
string_size = totalcharacters(location);
string = calloc(string_size, sizeof(char));
while((fgets (string, string_size, text)) != NULL)//getting strings from the text file.
{
for(count=0;(string[count]!=NULL);count++) //going through the characters of teh selected string here
{
if ((string[count]==10)||((string[count]>=58)&&(string[count]<=63))) fprintf(text2," "); //changing the new lines and other characters to spaces.
else
fputc(string[count],text2);//the original text file is now one long text string to the FILE pointer *text2
}
}
fclose (text);
fclose(text2);
text2=fopen(".\\textfiles\\temp.txt","r"); //the long text string is now read
while((fgets (string, string_size, text2)) != NULL)//getting strings from text file
{
currentword = strtok(string," \t\r\n"); //delimiting the strings so that words can be counted
while(currentword!=NULL)
{
countwords++;//number of words being counted
currentword = strtok(NULL," \t\r\n"); //null being put in place to follow by the last call strtok found a delimiter
}
}
fclose(text2);
return countwords;
}
As a side note, you need to check the return value from calloc() as well as from fopen().
P.S Please post your code in [code] tags rather than [PHP] tags.