Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

C stat() program(linux)

Status
Not open for further replies.

marsd

IS-IT--Management
Apr 25, 2001
2,218
US
Very inexperienced C guy here, but I've been programming
the shell and tcl for a couple of years. I have a script
with this code in it:

cat << EOF > $PWD/statfile.c
#include <stdio.h>
#include <unistd.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <sys/types.h>

int main(void) {
struct stat *fbuf = NULL;

if ( stat(&quot;$filename&quot;,fbuf) != 0) {
fprintf(stderr,&quot;%s, stat()\n&quot;,&quot;Error&quot;);
abort();
} else {
printf(&quot;%s ctime\n %s atime\n %s mtime\n&quot;, fbuf->st_ctime,
fbuf->st_atime, fbuf->st_mtime);
EXIT_SUCCESS;
}
}
EOF

Forgive the formatting,please.
I know there are things wrong with it, but being so
inexperienced with C is a problem. It segfaults.
I've run it through the debugger(gdb), but really
have yet to learn where it is wrong on my own.
I know there is an error in typing for the printf
call for one of the struct member pointers, but
am at a loss beyond this.

The remainder of the C relevant portions of the script looks like this so everyone can be sure that is not the cause:

if [ condition ] ; then
gcc statfile.c -o statout || a=&quot;Failed to compile.&quot;
test -z &quot;$a&quot; && chmod 700 statout && exec statout
echo &quot;C version.&quot;
rm $PWD/statout ; rm $PWD/statfile.c ; rm $PWD/statout
fi

TIA
 
Well, you shouldn't use a pointer declaration for buf. You declare there a pointer and set it to NULL, so no wonder that the function crashes.
Stat does not allocate memory for the structure passed.
Instead, you have to use a statically defined structure and pass its pointer to stat. Here goes:

Code:
int main(void) {
 struct stat fbuf;

 if ( stat(&quot;$filename&quot;,&fbuf) != 0) {
   fprintf(stderr,&quot;%s, stat()\n&quot;,&quot;Error&quot;);
   abort();
... rest of code

This should do it. Also, to get extended error information you can use the perror() function (try man for that to see exactly how that works).
[red]Nosferatu[/red]
We are what we eat...
There's no such thing as free meal...
once stated: methane@personal.ro
 
Thanks.
The problem was both the bad pointer declaration, and
mistyping the format to printf, but with some help I got it fixed.

Another problem:
How would you format the output of this program in proper
mo/day/hr type style?
I've tried a few things, but nothing works.
Something like: printf(&quot;%s\n&quot;,strftime(x,x,x,&fbuf.st_ctime));

Thanks.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top