Iterating through a Directory and storing the maximium file number as an integer

a hint

char name[16];
m = 0;
for (int i=0; i< 9999; i++)
{
sprintf(name, "%d.txt", i);
if (open name is successful)
{
m = i;
close name;
}
}

at the end m contains the highest file number