Monthly Archives: January 2014

Pract 1: System Calls (open(), read(), write(), close()) in C Language.

A system call is just what its name implies—a request for the operating system to do something on behalf of the user‘s program
1. open()
2. read()
3. write()
4. close()

1. open()
#include <fcntl.h>
int open( char *filename, int access, int permission );

The available access modes are
O_RDONLY    O_WRONLY     O_RDWR    O_APPEND    O_BINARY    O_TEXT
The permissions are
S_IWRITE    S_IREAD     S_IWRITE | S_IREAD

The open() function returns an integer value, which is used to refer to the file. If unsuccessful, it returns -1, and sets the global variable errno to indicate the error type.

2.read()
#include <fcntl.h>

int read( int handle, void *buffer, int nbyte );

The read() function attempts to read nbytes from the file associated with handle, and places the characters read into buffer. If the file is opened using O_TEXT, it removes carriage returns and detects the end of the file. The function returns the number of bytes read. On end-of-file, 0 is returned, on error it returns -1, setting errno to indicate the type of error that occurred.

3. write()

#include <fcntl.h>

int write( int handle, void *buffer, int nbyte );

The write() function attempts to write nbytes from buffer to the file associated with handle. On text files, it expands each LF to a CR/LF. The function returns the number of bytes written to the file. A return value of -1 indicates an error, with errno set appropriately.

4. close()

#include <fcntl.h>

int close( int handle );

The close() function closes the file associated with handle. The function returns 0 if successful, -1 to indicate an error, with errno set appropriately.

Implementation of open(), read(), write() and close() functions

Pract1.c

#include <stdio.h>
#include <fcntl.h>
int main()
{
int fd;
char buffer[80];
static char message[]=”Hello, SPCE – Visnagar”;
fd=open(“myfile.txt”,O_RDWR);
if (fd != -1)
{
printf(“myfile.txt opened with read/write access\n”);
write(fd,message,sizeof(message));
lseek(fd,0,0);
read(fd,buffer,sizeof(message));
printf(“%s — was written to myfile.txt \n”,buffer);
close(fd);
}
}

Note: First create empty file with myfile.txt before running the commands.

Commands:

# gcc –o pr pract1.c
# ./pr