Mam prośbe czy ktoś byłby w stanie dopisać dla tego kodu sortowania mozliwośc odczytu tekstu z dowolnego wybranego pliku i zapisu wyniku do pliku zewnętrznego
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct ENTRY
{
char word[50];
int count;
} ;
ENTRY* stats = 0;
int statsSize = 0;
int wordsStored = 0;
int growStats()
{
ENTRY* newStats = (ENTRY*)realloc (stats, (statsSize+100)*sizeof(ENTRY));
if (!newStats)
return 0;
stats = newStats;
statsSize += 100;
return 1;
}
int countWord(char*w)
{
for (int i=0; i<wordsStored; i++)
if (strcmp(w, stats[i].word) == 0)
{
stats[i].count++;
return 1;
}
if (wordsStored == statsSize)
if (!growStats())
return 0;
strcpy(stats[wordsStored].word, w);
stats[wordsStored].count = 1;
wordsStored++;
return 1;
}
int compare(const void* word1, const void* word2)
{
return ((ENTRY*)word2)->count - ((ENTRY*)word1)->count;
}
void main()
{
FILE* file = fopen ("alice", "r");
if (!file)
return;
for (int i=0; i<20; i++)
{
char word[50];
if (fscanf(file, "%49s", word) != 1)
{
puts("Error reading from file");
break;
}
if(!countWord(word))
{
puts ("Memory allocation fault");
break;
}
}
qsort(stats, wordsStored, sizeof(ENTRY), compare);
for (int w=0; w<20; w++)
printf("%s - %d/n", stats[w].word, stats[w].count);
if (stats)
free(stats);
fclose(file);
}