Operating System - HP-UX
1752579 Members
3076 Online
108788 Solutions
New Discussion юеВ

Re: Simple C program to process a UNIX file?

 
SOLVED
Go to solution
Peter Kempner
Occasional Contributor

Simple C program to process a UNIX file?

I want to write a C program that constantly loops around and checks the "last modified" date of a given file.

This file is a data file that is randomly ftp'd to me by someone else (always to the same place and with the same name).

I want to process the file if it is "new" ie if I haven't processed it before.

I have no idea how to do this easily.

Anyone have any ideas? many thanks....

Pete
3 REPLIES 3
A. Clay Stephenson
Acclaimed Contributor
Solution

Re: Simple C program to process a UNIX file?

The key to what you are trying to do is the stat() system call. Man 2 stat for details but doing this in C is drastic overkill. Perl has the stat function that is based on the underlying system call and will easily handle this task:

I'll attach a Perl Script that will do this quite easily and the rest can be a simple shell script:

#!/usr/bin/sh

TARGET="/xxx/yyy/myfile"
DELAY=300 # seconds

typeset -i LASTMTIME=0
typeset -i STAT=0

while [[ ${STAT} -eq 0 ]]
do
MTIME=$(fileage.pl -m -e ${TARGET})
STAT=${?}
if [[ ${STAT} -eq 0 ]]
then
if [[ ${LASTMTIME} -ne ${MTIME} ]]
then
if [[ ${LASTMTIME} -ne 0 ]]
then
# yor actual processing goes here
fi
LASTMTIME=${MTIME}
fi
sleep ${DELAY}
fi
done
exit ${STAT}

Invoke the perl script, fileage.pl w/o arguments for full usage.
If it ain't broke, I can fix that.
Hein van den Heuvel
Honored Contributor

Re: Simple C program to process a UNIX file?

A minimal "C" example.
Needs at least somem errno handling.

Hein.


#include
#include
#include
struct stat buf;
time_t st_ctime_last;
main (int argc, char *argv[])
{
while (!stat(argv[1], &buf)) {
if (buf.st_ctime > st_ctime_last) {
printf ("!\n");
st_ctime_last = buf.st_ctime;
} else {
printf (".\n");
}
sleep (5);
}
}

Peter Kempner
Occasional Contributor

Re: Simple C program to process a UNIX file?

Many thanks to both contributers. This forum never ceases to amaze me.

.. The really good side of human nature