Please explain why the answer is what is is thoroughly. I am trying to study for
ID: 3827661 • Letter: P
Question
Please explain why the answer is what is is thoroughly. I am trying to study for my test. I will make sure to thumbs up! thank you very much for your time
int count_characters(char *filename) {
char str[1001]; FILE* pFile;
int count = 0;
pFile = fopen(filename, "r");
if (pFile == NULL) {
printf ("Error opening file ");
return 0; }
while ( fgets (str, MAX_LEN, pFile ) != NULL ) {
count += strlen(str); }
fclose(pFile); return count;
}
16. Write the following function: int count characters (const char filename int n) The function should return the number of characters in the text file whose name is filename. If there is no character in the file or the file does not exit, the function should return 0. Assume the maximum number of characters in each line is 1000.Explanation / Answer
Function Explanation:
/* Function that counts and returns total number of characters in the file */
int count_characters(char *filename)
{
//Array to hold a single line of data. Since maximum number of characters is specified as 1000, size is declared as 1001
char str[1001];
//File Pointer
FILE* pFile;
//Variable for holding count
int count = 0;
//Opening file in read mode
pFile = fopen(filename, "r");
//If the file doesn't exist
if (pFile == NULL)
{
//Printing error message
printf ("Error opening file ");
//Return value 0
return 0;
}
/*
fgets function fetches a line of data from input file and stores in variable str
Loop gets iterated until entire data is processed
*/
while ( fgets (str, MAX_LEN, pFile ) != NULL )
{
/*
Finding the length of the current line using String function strlen
For eg: if variable str holds data as str = "Chegg India", strlen(str) returns value 11 (including space character)
Update the value of the variable count with calculated length
*/
count += strlen(str);
}
//Closing file
fclose(pFile);
/*
Return Count. If there is no data in the file, count will be 0
*/
return count;
}
Please let me know if you feel difficulty in understanding any part of this function.