《Makefile》
CC=gcc
TEXT=time
SVC=file_time.c debug.h
$(TEXT): $(SVC)
$(CC) -o $@ $^
clean:
rm -rf $(TEXT) *.o
*************************
《头文件》
/*Comment/uncomment the following line to disable/enable debugging,
OR define(or NOT) it in Makefile.
*/
//#define NDEBUG
#undef pr_debug /* undef it, just in case */
#ifndef NDEBUG
#ifdef __KERNEL__
/* This one if debugging is on, and kernel space */
#define pr_debug(fmt, args...) printk( KERN_ERR fmt, ## args)
#else
/* This one for user space */
#define pr_debug(fmt, args...) fprintf(stderr, fmt, ## args)
#endif
#else
#define pr_debug(fmt, args...) /* not debugging: nothing */
#endif
*************************
/* usage example: ./file_time test.txt */
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <assert.h>
#include <time.h>
#include "debug.h"
void usage (const char *s)
{
printf("usage:\n\t%s time_file\n", s);
}
int main(int argc, char **argv)
{
FILE *fp = NULL;
time_t seconds;
struct tm *pTime = NULL;
char buf[BUFSIZ];
int i = 0;
if(argc != 2) {
usage(argv[0]);
exit(1);
}
fp = fopen(argv[1], "a+");
assert(fp != NULL);
if (!fp ) {
usage(argv[0]);
exit(1);
}
fseek(fp, 0, SEEK_SET); //rewind(fp);
while(!feof(fp)) {
fgets(buf, BUFSIZ,fp);
if (buf[0] != EOF)
++i;
}
pr_debug("i =%d \n", i);
while(1) {
seconds = time (NULL);
pTime = localtime(&seconds);
assert(pTime);
sprintf(buf, "%d. %d-%d-%d %d:%d:%d\n", i++, pTime->tm_year+1900, pTime->tm_mon, pTime->tm_mday,
pTime->tm_hour, pTime->tm_min, pTime->tm_sec);
pr_debug("%s\n", buf);
fwrite(buf, strlen(buf), 1, fp);
fflush(fp);
sleep(1);
}
fclose(fp);
return 0;
}
***************
执行方式:./ time file_time
结果:
i =1
1. 2011-11-7 17:50:34
2. 2011-11-7 17:50:35
3. 2011-11-7 17:50:36
4. 2011-11-7 17:50:37
5. 2011-11-7 17:50:38
6. 2011-11-7 17:50:39
7. 2011-11-7 17:50:40
8. 2011-11-7 17:50:41
9. 2011-11-7 17:50:42
10. 2011-11-7 17:50:43
11. 2011-11-7 17:50:44
12. 2011-11-7 17:50:45
13. 2011-11-7 17:50:46
14. 2011-11-7 17:50:47
15. 2011-11-7 17:50:48
16. 2011-11-7 17:50:49
17. 2011-11-7 17:50:50