/* Open and lock file. Extract last record's number and record new record at end of file. Unlock and close file. Usage: key=`fbup filename "command"` Outputs on stdout the key value of new last record in file. Relies on UNIX flock working. Relies on the command being less than 1000 characters long */ /* Started: RJ Botting, Sep 1999 SunOS ftp 4.1.3_U1 2 sun4m Advice and quick reveiw by Dr. Y. Karant.Review: Y Karant */ #define MAXBUF 1024 #include #include #include #include #include #include #include main( argc, argv) int argc; char *argv[]; { int ans; /*answers to function calls*/ int datafd; /* file descriptor */ char line[MAXBUF]; int i; /*number characters in line*/ int lastkey, key; int noteof; /* not end of file yet*/ char ch; /*last input charcter*/ if(argc!=3){ fprintf(stderr, "Usage: %s filename \"command\".\n", argv[0]); exit(1); } /*fprintf(stderr, "DBUG1: %s %s %s\n",argv[0], argv[1], argv[2]);*/ datafd=open(argv[1], O_RDWR ); if( -1 == datafd){ fprintf(stderr, "Open %s failed with errno %d.\n", argv[1], errno); perror(""); exit(1); } /*fprintf(stderr, "DBUG2: %s %s %s: about to try lock\n",argv[0], argv[1], argv[2]);*/ ans= flock( datafd, LOCK_EX); if( -1 == ans ){ fprintf(stderr, "File locking (flock) returned %d with errno %d!\n", ans, errno ); perror(""); exit(2); } /*fprintf(stderr, "DBUG3: %s %s %s can access file\n", argv[0], argv[1], argv[2]);*/ /*-----------------------*/ /*start of data file*/ noteof= read( datafd, &ch, 1);/*read ahead*/ while(noteof){ /*start of line*/ i=0; while(noteof && ch!='\n' && i < MAXBUF - 1 ){ /*start char in line*/ line[i]=ch; i++; noteof=read( datafd, &ch, 1); }/*end char in line*/ while( noteof && ch!='\n' ){ /* char in rest of line*/ noteof=read( datafd, &ch, 1); }/*end char in rest of line*/ noteof=read( datafd, &ch, 1);/* end of line\n char*/ /*end of line*/ line[i]='\0'; i++; /*fprintf(stderr, "DBUG7: line = %s\n", line);*/ }/*end of file*/ /*fprintf(stderr, "DBUG8: last line = %s\n", line);*/ if( i == 0 || !sscanf(line, "%d", &lastkey) ){ /*Wot! No number?*/ lastkey=0; } key=lastkey+1; /*fprintf(stderr, "DBUG9: last key = %d, new key=%d\n", lastkey, key);*/ /* Warning following doesn't check argv[2] is less than MAXBUF-10 characters */ sprintf(line, "%d %s\n", key, argv[2]); /*fprintf(stderr, "DBUGA: new line will be %s\n", line);*/ lseek( datafd, 0, SEEK_END); write( datafd, line, strlen(line) ); printf("%d\n", key); /*-----------------------*/ /*fprintf(stderr, "DBUG4: %s %s %s: done it.\n", argv[0], argv[1], argv[2]);*/ ans=flock( datafd, LOCK_UN); /*fprintf(stderr, "DBUG5: %s %s %s: flock( datafd, LOCK_UN) returns %d\n", argv[0], argv[1], argv[2], ans);*/ if(ans== -1)perror(""); ans=close(datafd); if(ans== -1)perror(""); /*fprintf(stderr, "DBUG6: close returns %d\n", ans);*/ }