/*-------------------------------------------------------------------*/ /* testlowlevelio.c */ /* The creat, open, write, read, and close system calls. */ /*-------------------------------------------------------------------*/ #include #include #include int main(int argc, char *argv[]) { int iFd; int iRet; int iBytesWritten; int iBytesRead; char pcWriteBuffer[] = "hello"; char pcReadBuffer[6]; /* Write "hello" to a file named tempfile. */ iFd = creat("tempfile", 0644); if (iFd == -1) { perror(argv[0]); return 1; } iBytesWritten = 0; while (iBytesWritten < 6) { iRet = write(iFd, pcWriteBuffer + iBytesWritten, 6 - iBytesWritten); if (iRet == -1) { perror(argv[0]); return 1; } iBytesWritten += iRet; } iRet = close(iFd); if (iRet == -1) { perror(argv[0]); return 1; } /* Read "hello" from a file named tempfile. */ iFd = open("tempfile", O_RDONLY); if (iFd == -1) { perror(argv[0]); return 1; } iBytesRead = 0; while (iBytesRead < 6) { iRet = read(iFd, pcReadBuffer + iBytesRead, 6 - iBytesRead); if (iRet == -1) { perror(argv[0]); return 1; } iBytesRead += iRet; } iRet = close(iFd); if (iRet == -1) { perror(argv[0]); return 1; } /* Print the data to verify that the previous worked. */ printf("%s\n", pcReadBuffer); return 0; } /* Sample execution: --> gcc -Wall -ansi -pedantic -o testlowlevelio testlowlevelio.c --> testlowlevelio hello --> */