Operating System - HP-UX
1824636 Members
4785 Online
109672 Solutions
New Discussion юеВ

strange problem with "struct stat"

 
SOLVED
Go to solution
Suhas_3
Advisor

strange problem with "struct stat"

Hi..

I am facing strange problem with stat(...) call, sometime it works - some times it does not.

For following program -
=================== test-stat1.c ============
#include
main()
{
struct stat buf;
int nb;
if((stat("ex.man",buf)) != 0)
{
perror("ex.man");
exit(-1);
}
nb=buf.st_size;
printf("%d\n",nb);
}
========= end test-stat1.c ==============
it works perfectly.
But if i interchange lines 4 & 5 in the program, i.e. as follows - it does not work. That is, it prints value of nb as zero.
=========== test-stat2.c ============
#include
main()
{
int nb;
struct stat buf;
if((stat("ex.man",buf)) != 0)
{
perror("ex.man");
exit(-1);
}
nb=buf.st_size;
printf("%d\n",nb);
}
============= end test-stat2.c ===============

isn't it strange? I just declare int before struct and the program does not work. Morever, if I add some lines in the working program test-stat1.c, it stops working and prints value of nb as zero. i.e. consider expansion of program test-stat1.c
============= test-stat3.c ========
#include
main()
{
struct stat buf;
int nb;
/*
* some program lines added here,
* nothing is related to buf or nb
* .... */
....
.....
.....
.....

if((stat("ex.man",buf)) != 0)
{
perror("ex.man");
exit(-1);
}
nb=buf.st_size;
printf("%d\n",nb);
}
============== end program ==============
Now I get value of nb as zero again!!
One more strange observation is, if I put following line just before nb=buf.st_size; then the program works fine!! the line is -
printf("%s\n",buf);

Please let me know your views...
Am I missing something?
Thanks,
Suhas
3 REPLIES 3
Deepak Extross
Honored Contributor
Solution

Re: strange problem with "struct stat"

Suhas,

Do you get any error/warning while compiling?
AFAIK, stat() requires a POINTER to the struct stat.

Try replacing
if((stat("ex.man",buf)) != 0)
with
if((stat("ex.man",&buf)) != 0)

Good Luck!
Deepak Extross
Honored Contributor

Re: strange problem with "struct stat"

And if you're wondering why it mysteriously works 'sometimes', well, thats what happens when there's a corruption of memory (usually by incorrect use of pointers).

Trust me, if you get rid of the compiler warnings, all the ghosts in the machine will be exorcised!
Suhas_3
Advisor

Re: strange problem with "struct stat"

Thanks Deepak,
It worked!

It's really a problem when you do something wrong and still the program works - but that too sometimes! no way to know that you are doing wrong....