Pagini recente » Cod sursa (job #1127811) | Cod sursa (job #1798699) | Cod sursa (job #3217584) | Cod sursa (job #741428) | Cod sursa (job #462628)
Cod sursa(job #462628)
#include <stdio.h>
#include <stdlib.h>
//Read the text from the file
char* GetTextFromFile()
{
FILE* pFile = NULL;
long lSize = 0;
char* buffer = NULL;
size_t result = 0;
pFile = fopen ( "text.in" , "rb" );
if (pFile==NULL)
{
return NULL;
}
// obtain file size:
fseek (pFile , 0 , SEEK_END);
lSize = ftell (pFile);
rewind (pFile);
// allocate memory to contain the whole file:
buffer = (char*) malloc (sizeof(char) * (lSize + 1));
buffer[lSize] = 0; //mark the end of the string
if (buffer == NULL)
{
return NULL;
}
// copy the file into the buffer:
result = fread (buffer, 1, lSize, pFile);
if (result != lSize)
{
free(buffer);
return NULL;
}
/* the whole file is now loaded in the memory buffer. */
// terminate
fclose (pFile);
return buffer;
}
int isAlpha(char c)
{
int a = ((c >= 'A') && (c <= 'Z')) || ((c >= 'a') && (c <= 'z'));
return a;
}
int GetAverageWordLength(char* Text)
{
int WordsCount = 0;
int TotalWordsLength = 0;
int Average = 0;
int CrtPos = 1;
if (Text == NULL)
return 0;
//Parse the string
while (Text[CrtPos] != 0)
{
if (isAlpha(Text[CrtPos]))
{
TotalWordsLength++;
if (!isAlpha(Text[CrtPos-1]))
WordsCount++;
}
CrtPos++;
}
if (isAlpha(Text[0]))
{
TotalWordsLength++;
WordsCount++;
}
Average = ((WordsCount > 0) ? (TotalWordsLength / WordsCount) : 0);
return Average;
}
int main()
{
FILE* fOutput = NULL;
char* pText = NULL;
int AverageWordLength = 0;
pText = GetTextFromFile();
if (pText != NULL)
{
AverageWordLength = GetAverageWordLength(pText);
}
fOutput = fopen("Text.out", "w");
fprintf(fOutput, "%d", AverageWordLength);
free(pText);
fclose(fOutput);
return 0;
}