/*--------------------------------------------------------------------*/ /* testdupin.c */ /* Author: Bob Dondero Modified by Xiaoyan In August 2018 (add fstat() to check ) the status of a file */ /*--------------------------------------------------------------------*/ #include #include #include #include #include /*needed for fstat()*/ /*--------------------------------------------------------------------*/ /* Demonstrate the open(), close(), dup(), and fstat() system-level functions. As usual, argc is the command-line argument count, and argv contains the command-line arguments. Return 0. */ int main(int argc, char *argv[]) { enum {BUFFER_LENGTH = 100}; int iFd; int iRet; char acBuffer[BUFFER_LENGTH]; struct stat fInfo; iFd = open("tmpfile.txt", O_RDONLY); if (iFd == -1) {perror(argv[0]); exit(EXIT_FAILURE); } iRet = close(0); if (iRet == -1) {perror(argv[0]); exit(EXIT_FAILURE); } iRet = dup(iFd); if (iRet == -1) {perror(argv[0]); exit(EXIT_FAILURE); } iRet = close(iFd); if (iRet == -1) {perror(argv[0]); exit(EXIT_FAILURE); } fgets(acBuffer, BUFFER_LENGTH, stdin); /* Write the data to verify that the call of fgets worked. */ fputs(acBuffer, stdout); /* test whether a file descriptor is closed. Print a message if not. */ if (fstat(iFd, &fInfo)>=0){ printf("File descriptor %d is not closed!", iFd); } if (fstat(1, &fInfo)>=0){ printf("File descriptor %d is not closed!\n", 1); } return 0; } /*--------------------------------------------------------------------*/ /* Sample execution (assume tmpfile.txt has only one line which is "testing!!"): $ gcc217 testdupin.c -o testdupin $ ./testdupin testing!! File descriptor 1 is not closed! */