Here is the question:
Write a function that takes a file handle
f
as a parameter and returns the number of occurrences of all digits in the file found in the file. Write a program to show how this function can be used to find the number of digits in the file "abd.dat".
After I finished this question, I noticed it need a return in the function, I just do the print inside of the function. I made some try to modify the code to do the print in main()
function, but it seems not work, the output becomes weird.
#include <stdio.h>
#include <stdlib.h>
#define BASE 10
int digits(FILE *);
int main()
{
FILE *fp = fopen("abc.dat", r);
digits(fp);
fclose(fp);
return EXIT_SUCCESS;
}
int digits(FILE *f)
{
long long num, digits;
int i, lastDigit;
int occu[BASE];
fscanf(f, "%lld", &num);
for (i = 0; i < BASE; i++)
{
occu[i] = 0;
}
digits = num;
while (digits != 0)
{
lastDigit = digits % 10;
digits /= 10;
occu[lastDigit]++;
}
printf(Occurrences of each digit in %lld is: \n, num);
for (i = 0; i < BASE; i++)
{
printf("Occurrences of %d = %d\n", i, occu[i]);
}
}