Re: A Q for C gurus

Cameron Hutchison (camh@nospam.orthanc.apana.org.au)
Sat, 28 Jan 1995 14:14:08 +1000 (EST)

Once upon a time Anthony Young said...
>
> void main()
> {
> struct ffblk *f;
> struct stat *s;
> char dummy[1024];
>
> findfirst("*.*",f,63);
> strcpy(dummy,(f->ff_name));
> stat((f->ff_name),s);
> if (((s->st_mode) & S_IFDIR) == S_IFDIR)
> printf("%s\n",dummy);
> while ((findnext(f)) == 0) {
> strcpy(dummy,(f->ff_name));
> stat((f->ff_name),s);
> if (((s->st_mode) & S_IFDIR) == S_IFDIR)
> printf("%s\n",dummy);
> }
> }
>
> For some reason the stat function stuffed up (f->ff_name),

If you check the man page for stat(2v) you will see that you pass it a
pointer to a buffer (of type struct stat) in which to store the information.
You are passing in an uninittialised pointer (s), so it could quite likely
stuff up almost anything. Same goes for findfirst/findnext, 'f' never gets
initialised.

Change the declaration of 'f' and 's' to
struct ffblk f;
struct stat s;

and call findfirst/findnext and stat with the address of this structure...
findfirst("*.*", &f, 63);
findnext(&f);
stat(ff->f_name, &s);

You should now be able to get rid of the dummy buffer.

You've also got another problem with your check of a directory. The st_mode
member of stat struct does not use a bitmask to represent the file types
(they are mutually exclusive, therefore there's no need). You should extract
the the type with the S_IFMT bitmask and then compare to S_IFDIR.

Here's my piece of code, headers excluded [untested]

main()
{
struct ffblk f;
struct stat s;

findfirst("*.*", &f, 63);
do {
stat(f.ff-name, &s);
if ((s.st_mode & S_IFMT) == S_IFDIR)
printf("%s\n", f.ff_name);
} while (findnext(&f) == 0);
}

Cheers

-- 
Cameron Hutchison (camh@nospam.orthanc.apana.org.au) | Beware of the clams
GCS d--@nospam. -p+ c++(++++) l++ u+ e+ m+(-) s n- h++ f? !g w+ t r+