We don't do your homework, so we aren't going to fix it for you - that's an important development skill called debugging, which you only learn by using, not by watching.
So use your debugger.
Put a breakpoint on the first line of the scan_dir function, and step through the code looking at what exactly is going on. Work out what should happen as a result of each line before it is executed, and compare what did happen to that. If it did what you expected, then it;s fine, move on to the next. If it didn't, why not? What was the problem? Was it the code, or your expectations?
Try it: this is a valuable skill, and one which is best learned on simple tasks like this before you get to complicated tasks!
But I'd suggest that it would be a lot easier if you change your coding style: break scan_dir into separate tasks, so it handles a directory, and calls a separate function for each file. Then each file processes a set of lines via another method.
That way you are simplifying the code and separating the concerns and it should be easier to debug.
[edit]
Original OP question:
Hi, I have a directory which has multiple files.
Each file has a column of values.
I write a code which open the directory and open files one by one, calculate Min, Max and Average ¬
and then goes to the next file.
But there is a problem I can't get it?
!
!
Here is my code:
static void scan_dir(const char *dir)
{
struct dirent * entry;
DIR *d = opendir( dir );
if (d == 0) {
perror("opendir");
return;
}
while ((entry = readdir(d)) != 0)
{
printf("%s\n", entry->d_name);
FILE *sensor;
int num, min, max, sum, count, first;
sensor = fopen( entry->d_name, "r");
if (sensor != NULL)
{
for (sum = count = max = min = first = 0;
fscanf(sensor, "%d", &num) == 1; sum += num, ++count)
{
if (!first)
{
min = max = num; first = 1;
}
else if (num > max) max = num;
else if (num < min) min = num;
}
printf("count = %d, min = %d, max = %d, avg = %.1lf\n", count, min, max, sum / (double) count);
fclose(sensor);
}
else
{
printf("Unable to read file '%s'\n", entry->d_name );
}
}
closedir(d);
}
int main(int argc, char ** argv)
{
scan_dir(argv[1]);
return 0;
}
and here is the output:
1 file 1
2 count = 41, min = 1254, max = 1361, avg = 1298.3
3 ..
4 count = 0, min = 0, max = 0, avg = -nan
5 file 2
6 count = 41, min = 1865245, max = 1936860, avg = 1875714.9
7 file 3
8 count = 41, min = 0, max = 0, avg = 0.0
9 .
10 count = 0, min = 0, max = 0, avg = -nan
11 file 4
12 count = 41, min = 1, max = 1, avg = 1.0
Above, I don't know why lines "3,4,9,10" printed?
!
Actually they are not even related to any file!
So could somebody help me to correct the code?
[/edit]