Unix standard I/O

Standard I/O:
All the I/O routines centered around file descriptors. When a file is opened, a file descriptor is returned, and that descriptor is then used for all subsequent I/O operations. With the standard I/O library, the discussion centers around streams.
The system calls are as follows:
fopen():-
 The fopen() function opens the file whose name is the string pointed to by path and associates a stream with it.
Syntax:
            #include<stdio.h>
FILE  *fopen(const char *path,                  // path name                                                                                      const char *mode);               // permissions
Returns file pointer on success otherwise NULL on error.
The argument mode points to a string beginning with one of the following sequences:
r – Open text file for reading. The stream is positioned at the beginning of the file.
r+ – Open for reading and writing. The stream is positioned at the beginning of the file.
w– Truncate file to zero length or create text file for writing. The stream is positioned at the beginning of the file.
w+ – Open for reading and writing. The file is created if it does not exist, otherwise it is truncated. The stream is positioned at the beginning of the file.
a – Open for appending (writing at end of file). The file is created if it does not exist. The stream is positioned at the end of the file.
a+ – Open for reading and appending (writing at end of file). The file is created if it does not exist. The initial file position for reading is at the beginning of the file, but output is always appended to the end of the file.
fclose(): The fclose() function flushes the stream pointed to by fp (writing any buffered output data using fflush(2)) and closes the underlying file descriptor.
The behavior of fclose() is undefined if the stream parameter is an illegal pointer, or is a descriptor already passed to a previous invocation of fclose().
Syntax:
#include<stdio.h>
int fclose(FILE *fp);              // file pointer
The system call will return 0 on success. Otherwise, EOF is returned and the global variable errno is set to indicate the error. In either case any further access (including another call to fclose()) to the stream results in undefined behaviour.
fflush():
For output streams, fflush() forces a write of all user-space buffered data for the given output or update stream via the stream’s underlying write function. For input streams, fflush() discards any buffered data that has been fetched from the underlying file, but has not been by the application. The open status of the stream is unaffected.
Syntax:
#include<stdio.h>
int ffulsh(FILE *fp);              // file pointer
Upon successful completion 0 is returned. Otherwise, EOF is returned and errno is set to indicate error.
Types of unformatted I/O:
There are 3 types of unformatted I/O
·         Character at a time I/O: We can read or write one character at a time.
·         Line at a time I/O: We can read or write line at a time.
·         Direct I/O: This type of I/O is supported by the fread and fwrite functions
Character at a time I/O:
Three input functions allow us to read one character at a time.
                        #include <stdio.h>
                        int getc (FILE *fp);
                        int fgetc (FILE *fp);
                        int getchar (void);
All three return the character read as an unsigned char cast to an int or EOF on end of file or error.
An output function that corresponds to each of the input functions are:
                        #include <stdio.h>
                        int putc (int c, FILE *fp);
                        int fputc (int c, FILE *fp);
                        int putchar (int c);
All three return the character written as an unsigned char cast to an int or EOF on error.
Line at a time I/O:
fgets():
fgets() reads in at most one less than size characters from stream and stores them into the buffer pointed to by s. Reading stops after an EOF  or a new line. If a newline is read, it is stored into the buffer. A ‘’ is stored after the last character in the buffer.
Syntax:
#include<stdio.h>
char *fgets(char *buff, int size, FILE *fp);
This system call will return buff on success and NULL on error or when end of the file occurs while no characters have been read.
gets():
gets() reads a line from stdin into the buffer pointed to by buff until either a terminating newline or EOF, which it replaces with ‘’. No check for buffer overrun is performed.
Syntax:
#include<stdio.h>
char *gets(char *buff);
This system call will return buff on success, and NULL on error or when end of file occurs while no characters have been read.
fputs(): fputs() writes the string buffer to stream, without its trailing ‘’.
Syntax:
#include<stdio.h>
int fputs(const char *buff, FILE *fp);
This system call will return a non negative number on success, or EOF on error.
puts(): puts() writes the string buffer and a trailing newline to stdout.
Syntax:
#include<stdio.h>
int puts(const char *buff);
This system call will return a non negative number on success or EOF on error.
fseek():
The fseek() function sets the file position indicator for the stream pointed to by stream. The new position, measured in bytes, is obtained by adding offset bytes to the position specified by whence. If whence is set to SEEK_CUR, or SEEK_END, the offset is relative to the start of the file, the current position indicator, or end-of-file, respectively. A successful call to the fseek() function clears the end-of-file indicator for the stream and undoes any effects of the ungetc(3) function on the same stream.
Syntax:
#include<stdio.h>
int fseek(FILE *fp, long offset, int whence);
this system call will return current offset. Otherwise -1 is returned and errno is set to indicate the error.
Formatted I/O:
The formatted output system calls are
printf(),fprintf(),sprint(),snprintf().
The functions in the printf() family produce output according to a format as described below. The functions printf() write output to stdout. The standard output stread; fprintf() write output to the given output stream. Sprintf ,snprintf() write to the character string str.
Syntax:
#include<stdio.h>
int printf(const char *format,…);
int fprintf(FILE *fp, const char *format,…);
int sprint(char *str, const char *format,…);
int snprintf(char *str, size_t size, const char *format,…);
Upon successful return, these functions return the number of characters printed (not including the trailing ‘’ used to end output to strings). If an output error is encountered, a negative value is returned.
The formatted input system calls are
scanf(),fscanf(),sscanf().
The scanf() family of functions scans input according to format as described below. This format may contain conversion specifications; the results from such conversions, if any, are stored in the locations pointed to by the pointer arguments that follow format. Each pointer argument must be of a type that is appropriate for the value returned by the corresponding conversion specification.
Syntax:
#include<stdio.h>
int scanf(const char *format,…);
int fscanf(FILE *fp, const char *format,…);
int sscanf(const char *str, const char *format,…);
These functions returns the number of input items successfully matched and assigned, which can be fewer than provided for, or even zero in the event of an early matching failure.
The value EOF is returned if the end of input is reached before either the first successful conversion or a matching failure occurs. EOF is also returned if a read error occurs, in which case the error indicate for the stream(see ferror(2)) is set, and errno is set indicate the error.
Streams:
The standard streams are preconnected input and output channels between a computer program and its environment (typically a text terminal) when it begins execution.
When we open a stream, the standard I/O function fopen returns a pointer to a FILE object. This object is normally a structure that contains all the information required by the standard I/O library to manage the stream.
Standard Input, Standard Output, and Standard Error:
Three streams are predefined and automatically available to a process: standard input, standard output, and standard error. These streams refer to the same files as the file descriptors STDIN_FILENO, STDOUT_FILENO, and STDERR_FILENO.
These three standard I/O streams are referenced through the predefined file pointers stdin, stdout, and stderr. The file pointers are defined in the <stdio.h> header.
File Descriptors
Each UNIX process has a bunch of file descriptors at its disposal, numbered o through N, where N is the maximum. N depends on the version of UNIX and its configuration, but it’s always at least 16.
Standard File Descriptors
By convention, the first three file descriptors are already open when the process begins. File descriptor 0 is the standard input, file descriptor 1 is the standard output, and file descriptor 2 is the standard error output, which is usually open to the controlling terminal. Instead of numbers, it’s better to use the symbols STDIN_FILENO, STDDOUT_FILENO, STDERR_FILENO.
Any of these standard file descriptors could be open to a file, a pipe, a FIFO, a device, or even a socket.
Using File Descriptors
Generally, UNIX uses fd’s for anything that behaves in some way like a file, in that you can read it or write it or both. File descriptors aren’t used for less-file-like communication mechanisms, such as message queues, which you can’t read and write (there are specialized calls for the purpose).
Few waysà
. open, used for most things that have path name, including regular and special files and named pipes (FIFOs)
.pipe, which creates and opens an un-named pipe
.socket, accept and connect, which are used for networking.
File and directory maintenance:
Chmod:-
The chmod function change the file access permissions for owner, group and others as well as the  set-UID, set-GID and sticky flags. A process that calls one of these functions should have the effec­tive user ID of either the superuser or the owner of the file. The UNIX command is implemented based on the chmod API.
Syntax:-
#include <sys/types.h> or
#include <sys/stat.h> or
#include <unistd.h>
int chmod (const char* path, mode_t mode);
It returns 0 on success or -1 on error (sets errno).
The different types of permissions under mode_t mode are
·         S_ISUID        04000             set User-ID on execution
·         S_ISGID        02000             set Group-ID on execution
·         S_ISVTX        01000             Sticky bit
·         S_IRUSR       00400            read by owner
·         S_IWUSR       00200            write by owner
·         S_IXUSR       00100            execute by owner
·         S_IRGRP       00040            read by group
·         S_IWGRP       00020            write by group
·         S_IXGRP        00010            execute by group
·         S_IROTH       00004            read by others
·         S_IWOTH      00002            write by others
·         S_IXOTH       00001            execute by others
When the sticky bit is set on a directory, files in that directory may be unlinked or renamed only by root or their owner.
chown :-
chown changes the user-ID  and group-ID of a file. Only the or the super user may execute it. If either uid or gid is -1, the corresponding ID is left alone.
Chownàchange owner and group of file by path
Syntax :-
#include <unistd.h>
int chown (
const char *path,      /* pathname */
uid_t uid,                   /* new user ID */
gid_t gid                     /* new group ID */
);
Returns 0 on success or -1 on error (sets errno).
unlink:-
The unlink system call removes a link from a directory, reducing the link count in the i-node by one. If the resulting link count is zero, the file system will discard the file: All disk space that it used will be made available for reuse (added to the “free list”). The i-node will become available for reuse, too. The process must have write permission in the directory containing the link.
Any kind of file (regular, socket, named pipe, special etc) can be unlinked, but only a superuser can unlink a directory, and on some systems even the superuser can’t. In any case, the ‘rmdir’ system  call can be used for unlinking a directory, not unlink.
unlinkàremove directory entry
Syntax :-
#include <unistd.h>
int unlink(
const char *path       /* pathname */
);
Returns  0 on success or -1 on error (sets errno).
link :-
An entry in a directory, consisting of a name and an i-number, is called a hard link. The other kind of link is a symbolic link.
You get a hard link when a file of any type, including directory, is created. You can get additional hard links to non directories with the link system call.
Linkàcreate hard link
Syntax :-
#include <unistd.h>
int link (
const char *oldpath,            /* old pathname */
const char *newpath           /* new pathname */
);
Returns 0 on success or -1 on error (sets errno).
The first argument, oldpath, must be an existing link; it provides the i-number to be used. The second argument, newpath, indicates the name of the new link.
symlink:-
Unlike a hard link, where the i-number you want to link to goes right in the directory, a symbolic link is a small file containing the text of a path to the object you want to link to.
symlinkàcreate symbolic link
Syntax :-
#include <unistd.h>
int symlink(
const char *oldpath,             /* old pathname */
const char *newpath           /*possible new pathname */
);
Returns 0 on success or -1 on error (sets errno).
mkdir:- This function is used to make a directory.
Syntax :-
#include <sys/stat.h>
int mkdir(
const char *path,                  /* pathname */
mode_t  perms                      /* permissions */
);
Returns 0 on success or -1 on error (sets errno).
rmdir:- This function is used to remove the directory.
Syntax :-
#include <unistd.h>
int rmdir(
const char *path                   /* pathname */
);
Returns 0 on success or -1 on error (sets errno).
chdir:- This function is used to change the directory by path.
Syntax :-
#include <unistd.h>
int chdir(
const char *path                   /* pathname */
);
Returns  0 on success or -1 on error (sets errno).
getcwd:- This function is used to get current directory pathname.
Syntax :-
#include <unistd.h>
char *getcwd(
char  *buf,                  /* returned pathname */
size_t bufsize           /* size of buf */
);
Returns pathname or NULL on error (sets errno).
Directory handling system calls:
opendir: This function is used to open a directory.
Syntax :-
#include <dirent.h>
DIR *opendir(
const char *path                   /*directory pathname */
);
Returns DIR pointer or NULL on error (sets errno).
readdir:- This function is used to read a directory.
Syntax :-
#include <dirent.h>
struct dirent *readdir(
DIR *dirp                    /* DIR pointer from opendir */
);
Returns pointer on success or NULL on EOF  or  error (sets errno).
The structure contains at least the following two members:
struct dirent
 {
ino_t d_ino;                                       /* i-node number */
char d_name [NAME_MAX + 1];   /* null-terminated filename */
}
closedir :- This function is used to close directory.
Syntax  :-
#include <dirent.h>
int closedir(
DIR *dirp                                /* DIR pointer from opendir */
);
Returns 0 on success or -1 on error (sets errno).
rewinddir:- This function  is used to rewind directory i.e., sets the pointer to the starting position of the directory.
Syntax :-
#include <dirent.h>
void rewinddir(
DIR *dirp                    /* DIR pointer from opendir */
);
No return value.
seekdir:- This function is used to set the file pointer to the location where the user specified.
Syntax :-
#include <dirent.h>
void seekdir(
DIR *dirp,                   /* DIR pointer from opendir */
long loc                                  /* location */
);
No return value.
telldir:- This function is used to get the directory location.
Syntax :-
#include <dirent.h>
long telldir(
DIR *dirp                    /* DIR pointer from opendir */
);
Returns location (no error return).

Leave a Reply

Your email address will not be published. Required fields are marked *

Enable Notifications OK No thanks