C PROGRAMMING NOTE

 

In this "C PROGRAMMING NOTE 1", You can learn header files in c like stdio.h [ printf(), scanf(), getc(), putc(), fopen(), fclose(), remove(), flush() ], stdlib.h [ malloc(), free(), abort(), exit(), atol(), atoll(), atof(), rand() ], sys/types.h [ block, key, pthread, time, trace, uid ], sys/stat.h [ fstat(), lstat(), stat(), mode, link, id, time,st_mode file type, file mode bits ], dirent.h [ opendir, readdir, telldir, seekdir, rewinddir, or closedir subroutine ], and components of command line arguments, exit, return, return type topics. If you are a beginner then it will help you in your exams, and even competitive exams.

This C PROGRAMMING NOTE 1, covers C Statements and what is the functionality of it, is discussed in short.

HEADER FILES

 

HEADER FILE WITH DESCRIPTION

#include<stdio.h>

The header file "stdio.h" is written as #include<stdio.h>.

The #include preprocessor directive is used to paste the code of a given file into the current file. It is used to include system-defined and user-defined header files. If the included file is not found, the compiler renders an error.

The stdio.h stands for Standard Input-Output. It has information related to input-output functions, like,

  • printf() - It is used to print the strings, integer, character etc on the output screen.
  • scanf() - It reads the strings, integer, character etc from the keyboard.
  • getc() - It reads the character from the file.
  • putc() - It writes the character to the file.
  • fopen() - It opens the file and all file handling functions are defined in stdio.h header file.
  • fclose() - It closes the opened file.
  • remove() - It deletes the file.
  • fflush() - It flushes the file.

#include<stdlib.h>

The header file stdlib.h stands for Standard Library. It has information about memory allocation/freeing functions.

It has information related to memory allocation/freeing functions, like,

  • malloc() - It allocated the memory during execution of program
  • free() - It frees the allocated memory.
  • abort() - It terminates the C program.
  • exit() - It terminates the program and does not return any value.
  • atol() - It converts a string to long int.
  • atoll() - It converts a string to long long int.
  • atof() - It converts a string to a floating-point value.
  • rand() - It returns a random integer value.

include<SYS/TYPES.H>

The <sys/types.h> header shall include definitions for at least the following types:

  • blkcnt_t - Used for file block counts.
  • blksize_t - Used for block sizes.
  • clock_t - Used for system times in clock ticks or CLOCKS_PER_SEC;
  • clockid_t - Used for clock ID type in the clock and timer functions.
  • dev_t - Used for device IDs.
  • fsblkcnt_t - Used for file system block counts.
  • fsfilcnt_t - Used for file system file counts.
  • gid_t - Used for group IDs.
  • id_t - Used as a general identifier; can be used to contain at least a pid_t, uid_t, or gid_t
  • ino_t - Used for file serial numbers.
  • key_t - Used for XSI interprocess communication.
  • mode_t - Used for some file attributes.
  • nlink_t - Used for link counts.
  • off_t - Used for file sizes.
  • pid_t - Used for process IDs and process group IDs.
  • pthread_attr_t - Used to identify a thread attribute object.
  • pthread_barrier_t - Used to identify a barrier.
  • pthread_barrierattr_t - Used to define a barrier attributes object.
  • pthread_cond_t - Used for condition variables.
  • pthread_condattr_t - Used to identify a condition attribute object.
  • pthread_key_t - Used for thread-specific data keys.
  • pthread_mutex_t - Used for mutexes.
  • pthread_mutexattr_t - Used to identify a mutex attribute object
  • pthread_once_t - Used for dynamic package initialization.
  • pthread_rwlock_t - Used for read-write locks.
  • pthread_rwlockattr_t - Used for read-write lock attributes.
  • pthread_spinlock_t - Used to identify a spin lock.
  • pthread_t - Used to identify a thread.
  • size_t - Used for sizes of objects.
  • ssize_t - Used for a count of bytes or an error indication.
  • suseconds_t - Used for time in microseconds.
  • time_t - Used for time in seconds.
  • timer_t - Used for timer ID returned by timer_create().
  • trace_attr_t - Used to identify a trace stream attributes object
  • trace_event_id_t - Used to identify a trace event type.
  • trace_event_set_t - Used to identify a trace event type set.
  • trace_id_t - Used to identify a trace stream.
  • uid_t - Used for user IDs.
  • useconds_t - Used for time in microseconds.

In particular, the following are of special interest:

  • clock_t represents the system times in clock ticks.
  • dev_t is used for device numbers.
  • off_t is used for file sizes and offsets.
  • ptrdiff_t is the signed integral type for the result of subtracting two pointers.
  • size_t reflects the size, in bytes, of objects in memory.
  • ssize_t is used by functions that return a count of bytes or an error indication.
  • time_t counts time in seconds

#include<SYS/STAT.H>

The <sys/stat.h> header defines the structure of the data returned by the functions fstat(), lstat(), and stat().

The structure stat contains at least the following members:

dev_t     st_dev     ID of device containing file
ino_t     st_ino     file serial number
mode_t    st_mode    mode of file (see below)
nlink_t   st_nlink   number of links to the file
uid_t     st_uid     user ID of file
gid_t     st_gid     group ID of file
dev_t     st_rdev    device ID (if file is character or block special)
off_t     st_size    file size in bytes (if file is a regular file)
time_t    st_atime   time of last access
time_t    st_mtime   time of last data modification
time_t    st_ctime   time of last status change
blksize_t st_blksize a filesystem-specific preferred I/O block size for this object. In some filesystem types, this may vary from file to file 
blkcnt_t  st_blocks  number of blocks allocated for this object

File serial number and device ID taken together uniquely identify the file within the system. The blkcnt_t, blksize_t, dev_t, ino_t, mode_t, nlink_t, uid_t, gid_t, off_t and time_t types are defined as described in <sys/types.h>. Times are given in seconds.

The following symbolic names for the values of st_mode are also defined:

File type:

S_IFMT type of file; S_IFBLK block special; S_IFCHR character special; S_IFIFO FIFO special; S_IFREG regular; S_IFDIR directory; S_IFLNK symbolic link;

File mode bits:

S_IRWXU read, write, execute/search by the owner; S_IRUSR read permission, owner; S_IWUSR write permission, owner; S_IXUSR execute/search permission, owner; S_IRWXG read, write, execute/search by group; S_IRGRP read permission, group; S_IWGRP write permission, group; S_IXGRP execute/search permission, group; S_IRWXO read, write, execute/search by others; S_IROTH read permission, others; S_IWOTH write permission, others; S_IXOTH execute/search permission, others; S_ISUID set-user-ID on execution; S_ISGID set-group-ID on execution; S_ISVTX on directories, restricted deletion flag.

The bits defined by S_IRUSR, S_IWUSR, S_IXUSR, S_IRGRP, S_IWGRP, S_IXGRP, S_IROTH, S_IWOTH, S_IXOTH, S_ISUID, S_ISGID  and S_ISVTX are unique.

S_IRWXU is the bitwise OR of S_IRUSR, S_IWUSR and S_IXUSR.

S_IRWXG is the bitwise OR of S_IRGRP, S_IWGRP and S_IXGRP.

S_IRWXO is the bitwise OR of S_IROTH, S_IWOTH and S_IXOTH.

Implementations may OR other implementation-dependent bits into S_IRWXU, S_IRWXG and S_IRWXO, but they will not overlap any of the other bits defined in this document. The file permission bits are defined to be those corresponding to the bitwise inclusive OR of S_IRWXU, S_IRWXG and S_IRWXO.

The following macros will test whether a file is of the specified type. The value m supplied to the macros is the value of st_mode from a stat structure. The macro evaluates to a non-zero value if the test is true, 0 if the test is false.

S_ISBLK(m) Test for a block special file; S_ISCHR(m) Test for a character special file; S_ISDIR(m) Test for a directory; S_ISFIFO(m) Test for a pipe or FIFO special file; S_ISREG(m) Test for a regular file; S_ISLNK(m) Test for a symbolic link.

The implementation may implement message queues, semaphores, or shared memory objects as distinct file types.

The following are declared as functions and may also be defined as macros. Function prototypes must be provided for use with an ISO C compiler.

int    chmod(const char *, mode_t);
int    fchmod(int, mode_t);
int    fstat(int, struct stat *);
int    lstat(const char *, struct stat *);
int    mkdir(const char *, mode_t);
int    mkfifo(const char *, mode_t);
int    mknod(const char *, mode_t, dev_t);
int    stat(const char *, struct stat *);
mode_t umask(mode_t);

STAT()

The stat() function obtains information about the named file and writes it to the area pointed to by the buf argument. The path argument points to a pathname naming a file. Read, write, or execute permission of the named file is not required, but all directories listed in the pathname leading to the file must be searchable. An implementation that provides additional or alternate file access control mechanisms may, under implementation-dependent conditions, cause stat() to fail. In particular, the system may deny the existence of the file specified by path.

The buf argument is a pointer to a stat structure, as defined in the header <sys/stat.h>, into which information is placed concerning the file.

The stat() function updates any time-related fields, before writing into the stat structure.

The structure members st_mode, st_ino, st_dev, st_uid, st_gid, st_atime, st_ctime, and st_mtime will have meaningful values for all file types defined in this document. The value of the member st_nlink will be set to the number of links to the file.

RETURN: Upon successful completion, 0 is returned. Otherwise, -1 is returned and errno is set to indicate the error.

LSTAT()

The lstat() function has the same effect as stat(), except when the path refers to a symbolic link. In that case, lstat() returns information about the link, while stat() returns information about the file the link references.

For symbolic links, the st_mode member will contain meaningful information when used with the file type macros, and the st_size member will contain the length of the pathname contained in the symbolic link. File mode bits and the contents of the remaining members of the stat structure are unspecified. The value returned in the st_size member is the length of the contents of the symbolic link, and does not count any trailing null.

RETURN: Upon successful completion, lstat() returns 0. Otherwise, it returns -1 and sets errno to indicate the error.

#include<DIRENT.H>

The /usr/include/dirent.h file describes the format of a directory entry without reference to the type of underlying system.

The dirent structure, defined in the dirent.h file is used for directory access operations. Using these access operations and the dirent structure, along with its associated constants and macros, shields you from the details of implementing a directory and provides a consistent interface to directories across all types of file systems.

It also defines the structure dirent which includes the following members:

ino_t  d_ino       file serial number
char   d_name[]    name of entry

The type ino_t is defined as described in <sys/types.h>.

The character array d_name is of unspecified size, but the number of bytes preceding the terminating null byte will not exceed {NAME_MAX}.

The d_name field contains the name of the file in the context of the directory it traverses. So, it does not contain any path, just the name.

The following are declared as functions and may also be defined as macros. Function prototypes must be provided for use with an ISO C compiler.

int            closedir(DIR *);
DIR           *opendir(const char *);
struct dirent *readdir(DIR *);
int            readdir_r(DIR *, struct dirent *, struct dirent **);
void           rewinddir(DIR *);
void           seekdir(DIR *, long int);
long int       telldir(DIR *);

_D_NAME_MAX is a constant that indicates the maximum number of bytes in a file name for all file systems. (Related to this constant is the PATH_MAX constant, which specifies the maximum number of bytes in the full path name of a file, not including the terminating null byte.)

The value of the _D_NAME_MAX constant is specific to each type of filesystem type. It can be determined by using the pathconf or fpathconf subroutine.

The size of a dirent structure depends on the number of bytes in the file name.

OPENDIR, READDIR, TELLDIR, SEEKDIR, REWINDDIR, OR CLOSEDIR SUBROUTINE

Purpose: Performs operations on directories.

Syntax:

#include<dirent.h>

DIR *opendir (DirectoryName)
const char *DirectoryName;

struct dirent *readdir (DirectoryPointer)
DIR *DirectoryPointer;

long int telldir(DirectoryPointer)
DIR *DirectoryPointer;

void seekdir(DirectoryPointer,Location)
DIR *DirectoryPointer;
long Location;

void rewinddir (DirectoryPointer)
DIR *DirectoryPointer;

int closedir (DirectoryPointer)
DIR *DirectoryPointer;

Do not use the readdir subroutine in a multi threaded environment.

The opendir subroutine opens the directory designated by the DirectoryName parameter and associates a directory stream with it. An open directory must always be closed with the closedir subroutine to ensure that the next attempt to open that directory is successful.

The opendir subroutine also returns a pointer to identify the directory stream in subsequent operations. The null pointer is returned when the directory named by the DirectoryName parameter cannot be accessed or when not enough memory is available to hold the entire stream. A successful call to any of the exec functions closes any directory streams opened in the calling process.

The readdir subroutine returns a pointer to the next directory entry. The readdir subroutine returns entries for . (dot) and .. (dot dot), if present, but never returns an invalid entry (with d_ino set to 0). When it reaches the end of the directory, or when it detects an invalid seekdir operation, the readdir subroutine returns the null value. The returned pointer designates data that may be overwritten by another call to the readdir subroutine on the same directory stream. A call to the readdir subroutine on a different directory stream does not overwrite this data. The readdir subroutine marks the st_atime field of the directory for an update each time the directory is actually read.

The telldir subroutine returns the current location associated with the specified directory stream.

The seekdir subroutine sets the position of the next readdir subroutine operation on the directory stream. An attempt to seek an invalid location causes the readdir subroutine to return the null value the next time it is called. The position should be returned by a previous telldir subroutine call.

The rewinddir subroutine resets the position of the specified directory stream to the beginning of the directory.

The closedir subroutine closes a directory stream and frees the structure associated with the DirectoryPointer parameter.

If you use the fork subroutine to create a new process from an existing one, either the parent or the child (but not both) may continue processing the directory stream using the readdir, rewinddir, or seekdir subroutine.

Parameters

DirectoryNameNames the directory.
DirectoryPointerPoints to the DIR structure of an open directory.
LocationSpecifies the offset of an entry relative to the start of the directory.

Return Values

On successful completion, the opendir subroutine returns a pointer to an object of type DIR. Otherwise, a null value is returned and the errno global variable is set to indicate the error.

On successful completion, the readdir subroutine returns a pointer to an object of type struct dirent. Otherwise, a null value is returned and the errno global variable is set to indicate the error. When the end of the directory is encountered, a null value is returned and the errno global variable is not changed by this function call.

On successful completion, the closedir subroutine returns a value of 0. Otherwise, a value of -1 is returned and the errno global variable is set to indicate the error.


 
Source Code to Executable Code

COMPONENTS OF COMMAND LINE ARGUMENTS

Command line arguments are simply arguments that are specified after the name of the program in the system's command line, and these argument values are passed on to your program during program execution.

There are 2 components of Command Line Argument in C:

  1. argc: It refers to "argument count". It is the first parameter that we use to store the number of command-line arguments. It is important to note that the value of argc should be greater than or equal to 0.
  2. argv: It refers to "argument vector". It is basically an array of character pointer which we use to list all the command line arguments.

In order to implement command-line arguments, generally, 2 parameters are passed into the main function:

  1. Number of command-line arguments
  2. The list of command-line arguments

Syntax:

int main( int argc, char *argv[] )
{
// BODY OF THE MAIN FUNCTION
}
or it can also be written as
int main( int argc, char **argv[] )
{
// BODY OF THE MAIN FUNCTION
}

Example :

//Here is a code in C that illustrates the use of command-line arguments.
#include
int main(int argc, char** argv)
{
printf("Welcome to Shout Coders.\n");
int i;
printf("The number of arguments are: %d\n",argc);
printf("The arguments are:");
for ( i = 0; i < argc; i++)
printf("%s\n", argv[i]);
printf("\n");
return 0;
}

Output:
@Terminal> gcc scprg.c
@Terminal> ./a.out Saif
Welcome to Shout Coders.
The number of arguments are: 2
The arguments are:./a.out
Saif

EXIT()

The C library function void exit(int status) terminates the calling process immediately. It takes single parameter, This is the status value returned to the parent process. This function does not return any value since return type is VOID. An example is given below,

EXAMPLE:

#include<stdio.h>
#include<stdlib.h>
int main()
{
printf("\n Process Started ");
printf("\n Process Exit ");
exit(0);
printf("\n Process Ended ");
return 0;
}

Output:
@Terminal> gcc scprg.c
@Terminal> ./a.out
Process Started
Process Exit

RETURN

A return statement ends the execution of a function and returns control to the calling function. Execution resumes in the calling function at the point immediately following the call. A return statement can return a value to the calling function.

Syntax:

return (expression);

The value of the expression, if present, is returned to the calling function. If the expression is omitted, the return value of the function is undefined. The expression, if present, is evaluated and then converted to the type returned by the function. When a return statement contains an expression in functions that have a void return type, the compiler generates a warning, and the expression isn't evaluated.

If no return statement appears in a function definition, control automatically returns to the calling function after the last statement of the called function is executed. In this case, the return value of the called function is undefined. If the function has a return type other than void, it's a serious bug, and the compiler prints a warning diagnostic message. If the function has a void return type, this behavior is okay, but maybe considered poor style. Use a plain return statement to make your intent clear.

As a good engineering practice, always specify a return type for your functions. If a return value isn't required, declare the function to have void return type. If a return type isn't specified, the C compiler assumes a default return type of int.

Many programmers use parentheses to enclose the expression argument of the return statement. However, C doesn't require the parentheses.

The compiler may issue a warning diagnostic message about unreachable code if it finds any statements placed after the return statement.

In a main function, the return statement and expression are optional. What happens to the returned value, if one is specified, depends on the implementation.

EXAMPLE:

#include<stdio.h>
int retfun()
{
printf(" I'm inside function.\n");
printf(" I'm returning from function.\n");
return (1);
}
int main()
{
printf("\nFunction call\n ");
int value= retfun();
printf("Function returned value is: %d ",value);
return 0;
}

Output:
Function call
I'm inside function.
I'm returning from function.
Function returned value is: 1

RETURN TYPE

The return type of a function establishes the size and type of the value returned by the function.

TYPE-SPECIFIER
    void
    char
    short
    int 
    long
    float
    double
    signed
    unsigned
    struct-or-union-specifier
    enum-specifier
    typedef-name

The type-specifier can specify any fundamental, structure, or union type. If you do not include type-specifier, the return type int is assumed.

The return type given in the function definition must match the return type in declarations of the function elsewhere in the program. A function returns a value when a return statement containing an expression is executed. The expression is evaluated, converted to the return value type if necessary, and returned to the point at which the function was called. If a function is declared with a return type void, a return statement containing an expression generates a warning and the expression is not evaluated.

If you are a beginner, learn C Programming language first, because it helps you to understand how datatype works internally.

Comments

Popular posts from this blog

CONSTRUCTOR & DESTRUCTOR

MATRIX MULTIPLICATION