0% found this document useful (0 votes)
14 views

Programing in C

The document provides an overview of UNIX and Linux operating systems, detailing their history, structure, and key differences. It covers basic UNIX commands, shell programming, and preprocessor directives in C, emphasizing the functionalities and advantages of both operating systems. Additionally, it highlights the importance of understanding these systems for effective programming and system management.

Uploaded by

hiniyasrip
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Programing in C

The document provides an overview of UNIX and Linux operating systems, detailing their history, structure, and key differences. It covers basic UNIX commands, shell programming, and preprocessor directives in C, emphasizing the functionalities and advantages of both operating systems. Additionally, it highlights the importance of understanding these systems for effective programming and system management.

Uploaded by

hiniyasrip
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

GRT INSTITUTE OF

ENGINEERING AND
TECHNOLOGY,Tiruttani
(An Autonomous Institution)
Accredited by NBA (ECE), NAAC with “A++” Grade &An ISO 9001:2015 Certified Institution
Approved by AICTE, New Delhi& Affiliated to Anna University, Chennai.

DEPARTMENT OF SCIENCE AND HUMANITIES


ACADEMIC YEAR 2024-2025 (EVEN SEMESTER)
I CSE / II SEMESTER
CS24201- C LANGUAGE PROGRAMMING
ASSIGNMENT – I
1. Introduction to UNIX/LINUX – Basic Commands- Unix shell Programming
What is UNIX?

UNIX is an operating system which was first developed in the 1960s, and has been under
constant development ever since. By operating system, we mean the suite of programs which
make the computer work. It is a stable, multi-user, multi-tasking system for servers, desktops
and laptops.
UNIX systems also have a graphical user interface (GUI) similar to Microsoft Windows which
provides an easy to use environment. However, knowledge of UNIX is required for operations
which aren't covered by a graphical program, or for when there is no windows interface
available, for example, in a telnet session.
Types of UNIX

There are many different versions of UNIX, although they share common similarities. The
most popular varieties of UNIX are Sun Solaris, GNU/Linux, and MacOS X. Linux in its turn is
packaged in a form known as a Linux distribution. There are several Linux distributions, both
free and commercial.
ISU has a campus site subscription to Red Hat Enterprise Linux (RHEL), providing access for
university-owned equipment as well as personal access to students, faculty, and staff. All our
clusters are running RHEL.
The UNIX operating system
The UNIX operating system is made up of three parts; the kernel, the shell and the programs.
The kernel
The kernel of UNIX is the hub of the operating system: it allocates time and memory to
programs and handles the filestore and communications in response to system calls.
As an illustration of the way that the shell and the kernel work together, suppose a user
types rm myfile (which has the effect of removing the file myfile). The shell searches the
filestore for the file containing the program rm, and then requests the kernel, through system
calls, to execute the program rm on myfile. When the process rm myfile has finished running,
the shell then returns the UNIX prompt % to the user, indicating that it is waiting for further
commands.
The shell
The shell acts as an interface between the user and the kernel. When a user logs in, the login
program checks the username and password, and then starts another program called the shell.
The shell is a command line interpreter (CLI). It interprets the commands the user types in and
arranges for them to be carried out. The commands are themselves programs: when they
terminate, the shell gives the user another prompt (% on our systems).
The adept user can customise his/her own shell, and users can use different shells on the same
machine. Most accounts on our clusters have the bash shell by default. The accounts on hpc-
class use shell specified at https://asw.iastate.edu/cgi-bin/acropolis/user/shell .
The bash and tcsh shells have certain features to help the user inputting commands.
Filename Completion - By typing part of the name of a command, filename or directory and
pressing the [Tab] key, the shell will complete the rest of the name automatically. If the shell
finds more than one name beginning with those letters you have typed, it will beep, prompting
you to type a few more letters before pressing the tab key again.
History - The shell keeps a list of the commands you have typed in. If you need to repeat a
command, use the cursor keys to scroll up and down the list or type history for a list of previous
commands.
What is Linux?
Linux is a free and open-source family of operating systems that is resilient and flexible. In 1991,
an individual by the name as Linus Torvalds constructed it. The system’s source code is
accessible to everyone for anyone to look at and change, making it cool that anyone can see how
the system works. People from all across the world are urged to work together and keep
developing Linux due to its openness.
Since the beginning, Linux has grown into a dependable and safe OS that is used in an array of
gadgets, including PCs, cell phones, and huge supercomputers. It is well-known for being cost-
effective, which implies that employing it doesn’t cost a lot, and efficient, which indicates it can
complete a lot of jobs quickly.
What is Linux Operating System?
Developed by Linus Torvalds in 1991, the Linux operating system is a powerful and flexible
open-source software platform. It acts as the basis for a variety of devices, such embedded
systems, cell phones, servers, and personal computers. Linux, that’s well-known for its reliability,
safety, and flexibility, allows users to customize and improve their environment to suit specific
needs. With an extensive and active community supporting it, Linux is an appealing choice for
people as well as companies due to its wealth of resources and constant developments.
Difference Between Unix and Linux
Linux is essentially a clone of Unix. But, basic differences are shown below:
Linux Unix

The source code of Linux is freely The source code of Unix is not freely
available to its users available general public

It has graphical user interface along with


It only has command line interface
command line interface

Linux OS is portable, flexible, and can be


Unix OS is not portable
executed in different hard drives

Different versions of Linux OS are


Different version of Unix are AIS, HP-
Ubuntu, Linux Mint, RedHat Enterprise
UX, BSD, Iris, etc.
Linux, Solaris, etc.

The file systems supported by Linux are


as follows: xfs, ramfs, vfat, cramfsm, The file systems supported by Unix are as
ext3, ext4, ext2, ext1, ufs, autofs, devpts, follows: zfs, js, hfx, gps, xfs, vxfs
ntfs

Linux is an open-source operating system Unix is a proprietary operating system


that was first released in 1991 by Linus that was originally developed by AT&T
Torvalds. Bell Labs in the mid 1960s.

The Linux kernel is monolithic, meaning The Unix kernel is modular, meaning that
that all of its services are provided by a it is made up of a collection of
single kernel. independent modules that can be loaded
and unloaded dynamically.

Unix was originally designed to run on


large, expensive mainframe computers,
Linux has much broader hardware
while Linux was designed to run on
support than Unix.
commodity hardware like PCs and
servers.

User Interface of Linux is Graphical or


User Interface of unix is text-based.
text-based.

Command Line Interface of Linux is Command Line Interface of unix is


Bash, Zsh, Tcsh. Bourne, Korn, C, Zsh.
Advantages of UNIX
1. Stability: UNIX is known for its stability and reliability. It can run for long periods of
time without requiring a reboot, which makes it ideal for critical systems that need to run
continuously.
2. Security: UNIX has a robust security model that includes file permissions, user accounts,
and network security features. This makes it a popular choice for systems that require high
levels of security.
3. Scalability: UNIX can be scaled up to handle large workloads and can be used on a
variety of hardware platforms.
4. Flexibility: UNIX is highly customizable and can be configured to suit a wide range of
needs. It can be used for everything from simple desktop systems to complex server
environments.
5. Command-line interface: UNIX’s command-line interface allows for powerful and
efficient interaction with the system.
Disadvantages of UNIX
1. Complexity: UNIX can be complex and difficult to learn for users who are used to
graphical user interfaces ( GUIs ).
2. Cost: Some UNIX systems can be expensive, especially when compared to open-source
alternatives like Linux.
3. Lack of standardization: There are many different versions of UNIX, which can make it
difficult to ensure compatibility between different systems.
4. Limited software availability: Some specialized software may not be available for UNIX
systems.
5. Steep learning curve: UNIX requires a certain level of technical knowledge and
expertise, which can make it challenging for novice users.

UNIX BASIC COMMANDS


Getting help in Unix
 man – view manual pages for Unix commands
Unix Shell Commands
 clear – clear screen
 history – show history of previous commands
Time and Date commands
 date – show current date and time
 sleep – wait for a given number of seconds
 uptime – find out how long the system has been up
Unix users commands
These commands allow you to get basic information about Unix users in your environment.
 whoami – show your username
 id – print user identity
 groups – show which groups user belongs to
 passwd – change user password
 who – find out who is logged into the system
 last – show history of logins into the system
Unix file operations
Navigating filesystem and managing files and access permissions:
 ls – list files and directories
 cp – copy files (work in progress)
 rm – remove files and directories (work in progress)
 mv – move or rename files and directories to another location
 chmod – change file/directory access permissions
 chown – change file/directory ownership
Text file operations in Unix
Most of important configuration in Unix is in clear text files, these commands will let you quickly
inspect files or view logs:
 cat – concatenate files and show contents to the standard output
 more – basic pagination when viewing text files or parsing Unix commands output
 less – an improved pagination tool for viewing text files (better than more command)
 head – show the first 10 lines of text file (you can specify any number of lines)
 tail – show the last 10 lines of text file (any number can be specified)
 grep – search for patterns in text files
Unix directory management commands
Navigating filesystems and managing directories:
 cd – change directory
 pwd – confirm current directory
 ln – make links and symlinks to files and directories
 mkdir – make new directory
 rmdir – remove directories in Unix
Unix system status commands
Most useful commands for reviewing hostname configuration and vital stats:
 hostname – show or set server hostname
 w – display system load, who’s logged in and what they are doing
 uname – print Unix system information
Reboot
 shutdown – graceful shutdown and reboot of your system
 halt – ungraceful (without stopping OS services) shutdown
 reboot – ungraceful reboot (without stopping OS services)
Networking commands in Unix
Most useful commands for inspecting network setup and exploring network connections and ports:
 ifconfig – show and set IP addresses (found almost everywhere)
 ip – show and set IP addresses (in recent Linux versions)
 ping – check if remote host is reachable via ICMP ping
 netstat – show network stats and routing information
Process management
Listing processes and confirming their status, and stopping processes if needed:
 ps – list processes
 top – show tasks and system status (check out htop as well)
 kill – kill a process (stop application running)
Remote access commands
ssh is really the only way to go, but it’s important to know telnet as well:
 telnet – clear-text (insecure) remote access protocol
 ssh – Secure SHell – encrypted remote access client
o check out the SSH reference!
File transfers commands
Always useful to know how to copy files between servers or just download some package from the
web:
 ftp – clear-text (insecure!) File Transfer Protocol client
 sftp – secure (encrypted) version of FTP
 scp – secure (encrypted) version of cp command
 wget – download files from remote servers, HTTP/HTTPS and FTP
 curl – download files from remote servers, HTTP/HTTPS and FTP

Shell Programming
A shell script is a computer program designed to be run by the Unix/Linux shell which could be one
of the following:
 The Bourne Shell
 The C Shell
 The Korn Shell
 The GNU Bourne-Again Shell
A shell is a command-line interpreter and typical operations performed by shell scripts include file
manipulation, program execution, and printing text.
Extended Shell Scripts
Shell scripts have several required constructs that tell the shell environment what to do and when to
do it. Of course, most scripts are more complex than the above one.
The shell is, after all, a real programming language, complete with variables, control structures, and
so forth. No matter how complicated a script gets, it is still just a list of commands executed
sequentially.
The following script uses the read command which takes the input from the keyboard and assigns it
as the value of the variable PERSON and finally prints it on STDOUT.
#!/bin/sh
# Author : Zara Ali
# Copyright (c) Tutorialspoint.com
# Script follows here:
echo "What is your name?"
read PERSON
echo "Hello, $PERSON"
2. Preprocessor Directives
Preprocessors are programs that process the source code before the actual compilation begins. It
is not the part of compilation, but a separate process that allows programmers to modify the code
before compilation. It is the first process that the C source code goes through while being
converted to executable file.
Preprocessor Directives
The preprocessor directives are the instructions to the preprocessor for doing some tasks such as
text substitutions, macro expansions, including header files, and many more before compiling the
code. All of these preprocessor directives begin with a ‘#’ hash symbol.
One of the most commonly used preprocessors is #include which is used to include the header
files for different libraries in C programs. C provides more directives for different functionalities.
ist of Preprocessor Directives
The following table lists all the preprocessor directives in C:
Preprocessor Directives Description

#define Used to define a macro

#undef Used to undefine a macro

Used to include a file in the source code


#include
program

Used to include a section of code if a certain


#ifdef
macro is defined by #define

Used to include a section of code if a certain


#ifndef
macro is not defined by #define

#if Check for the specified condition

#else Alternate code that executes when #if fails

#elif Combines else and if for another condition check

#endif Used to mark the end of #if, #ifdef, and #ifndef


These preprocessors can be classified based on the type of function they perform.
Types of C Preprocessors
All the above preprocessors can be classified into 4 types:
Table of Content
 Macros
 File Inclusion
 Conditional Compilation
 Other Directives
Let us now learn about each of these directives in detail.
Macros
Macros are used to define constants or create functions that are substituted by the preprocessor
before the code is compiled. The two preprocessors #define and #undef are used to create and
remove macros in C.
#define token value
#undef token
where after preprocessing, the token will be expanded to its value in the program.
Example:
#include <stdio.h>

// Macro Definition
#define LIMIT 5
int main(){
for (int i = 0; i < LIMIT; i++) {
printf("%d \n", i);
}
return 0;
}
In the above program, before the compilation begins, the word LIMIT is replaced with 5. The
word ‘LIMIT’ in the macro definition is called a macro template and ‘5’ is macro expansion.
Note There is no semi-colon (;) at the end of the macro definition. Macro definitions do not need
a semi-colon to end.
There are also some Predefined Macros in C which are useful in providing various functionalities
to our program.
A macro defined previously can be undefined using #undef preprocessor. For example, in the
above code,
#include <stdio.h>

// Macro Definition
#define LIMIT 5

// Undefine macro
#undef LIMIT

int main(){
for (int i = 0; i < LIMIT; i++) {
printf("%d \n", i);
}
return 0;
}

Macros With Arguments


We can also pass arguments to macros. These macros work similarly to functions. For example,
#define foo(a, b) a + b
#define func(r) r * r
Let us understand this with a program:
#include <stdio.h>

// macro with parameter


#define AREA(l, b) (l * b)

int main(){
int a = 10, b = 5;

// Finding area using above macro


printf("%d", AREA(a, b));
return 0;
}

File Inclusion
File inclusion allows you to include external files (header files, libraries, etc.) into the current
program. This is typically done using the #include directive, which can include both system and
user-defined files.
Syntax
There are two ways to include header files.
#include <file_name>
#include “filename”
The ‘<‘ and ‘>’ brackets tell the compiler to look for the file in the standard
directory while double quotes ( ” ” ) tell the compiler to search for the header file in the source
file’s directory.
Example:
// Includes the standard I/O library
#include <stdio.h>

int main() {
printf("Hello World");

return 0;
}

Conditional compilation allows you to include or exclude parts of the code depending on certain
conditions. This is useful for creating platform-specific code or for debugging. There are the following
conditional preprocessor directives: #if, #ifdef, #ifndef, else, #elif and #endif
Syntax
The general syntax of conditional preprocessors is:
#if
// some code
#elif
// some more code
#else
// Some more code
#endif

3. Compilation Process
The compilation is the process of converting the source code of the C language into machine
code. As C is a mid-level language, it needs a compiler to convert it into an executable code so
that the program can be run on our machine.
The C program goes through the following phases during compilation:

Understanding the compilation process in C helps developers optimize their programs.


How do we compile and run a C program?
We first need a compiler and a code editor to compile and run a C Program. The below example
is of an Ubuntu machine with GCC compiler.
Step 1: Creating a C Source File
We first create a C program using an editor and save the file as filename.c
$ vi filename.c
We can write a simple hello world program and save it.
Step 2: Compiling using GCC compiler
We use the following command in the terminal for compiling our filename.c source file
$ gcc filename.c –o filename
We can pass many instructions to the GCC compiler to different tasks such as:
 The option -Wall enables all compiler’s warning messages. This option is recommended
to generate better code.
 The option -o is used to specify the output file name. If we do not use this option, then an
output file with the name a.out is generated.
If there are no errors in our C program, the executable file of the C program will be generated.
Step 3: Executing the program
After compilation executable is generated and we run the generated executable using the below
command.
$ ./filename

4 String Handling Functions in C


The C string functions are built-in functions that can be used for various operations and
manipulations on strings. These string functions make it easier to perform tasks such as
string copy, concatenation, comparison, length, etc. The <string.h> header file contains these
string functions.
i.)strlen()
The strlen() function is used to find the length of a string. It returns the number of characters in a
string, excluding the null terminator (‘\0’).
Example
#include <stdio.h>
#include <string.h>

int main() {
char s[] = "Gfg";

// Finding and printing length of string s


printf("%lu", strlen(s));
return 0;
}

Output
3
ii)strcpy()
The strcpy() function copies a string from the source to the destination. It copies the entire string,
including the null terminator.
Example:
#include <stdio.h>
#include <string.h>

int main() {
char src[] = "Hello";
char dest[20];

// Copies "Hello" to dest


strcpy(dest, src);
printf("%s", dest);
return 0;
}

Output
Hello
iii)strncpy()
The strncpy() function is similar to strcpy(), but it copies at most n bytes from source to
destination string. If source is shorter than n, strncpy() adds a null character to destination to
ensure n characters are written.
Example:
#include <stdio.h>
#include <string.h>

int main() {
char src[] = "Hello";
char dest[20];

// Copies "Hello" to dest


strncpy(dest, src, 4);
printf("%s", dest);
return 0;
}

Output
Hell
iv)strcat()
The strcat() function is used to concatenate (append) one string to the end of another. It appends
the source string to the destination string, replacing the null terminator of the destination with the
source string’s content.
Example
#include <stdio.h>
#include <string.h>

int main() {
char s1[30] = "Hello, ";
char s2[] = "Geeks!";

// Appends "Geeks!" to "Hello, "


strcat(s1, s2);
printf("%s", s1);
return 0;
}

Output
Hello, Geeks!
v)strncat()
In C, there is a function strncat() similar to strcat(). This function appends not more than n
characters from the string pointed to by source to the end of the string pointed to by destination
plus a terminating NULL character.
Example:
#include <stdio.h>
#include <string.h>
int main() {
char s1[30] = "Hello, ";
char s2[] = "Geeks!";

// Appends "Geeks!" to "Hello, "


strncat(s1, s2, 4);
printf("%s", s1);
return 0;
}

Output
Hello, Geek
vi)strcmp()
The strcmp() is a built-in library function in C. This function takes two strings as arguments,
compares these two strings lexicographically and returns an integer value as a result of
comparison.
Example
#include <stdio.h>
#include <string.h>

int main() {
char s1[] = "Apple";
char s2[] = "Applet";

// Compare two strings and print result


int res = strcmp(s1, s2);
if (res == 0) printf("s1 and s2 are same");
else if (res < 0)
printf("s1 is lexicographically smaller than s2");
else
printf("s1 is lexicographically greater than s2");
return 0;
}

Output
s1 is lexicographically greater than s2
vii)strncmp()
This function lexicographically compares the first n characters from the two null-terminated
strings and returns an integer based on the outcome.
Example:
#include <stdio.h>
#include <string.h>

int main() {
char s1[] = "Apple";
char s2[] = "Applet";

// Compare two strings upto 4 characters and print result


int res = strncmp(s1, s2, 4);
if (res == 0) printf("s1 and s2 are same");
else if (res < 0)
printf("s1 is lexicographically smaller than s2");
else
printf("s1 is lexicographically greater than s2");
return 0;
}

Output
s1 and s2 are same
viii)strchr()
The strchr() function is used to locate the first occurrence of a character in a string. If the
character is found, it returns a pointer to the first occurrence of the character; otherwise, it returns
NULL.
Example:
#include <stdio.h>
#include <string.h>

int main() {
char s[] = "Hello, World!";

// Finding the first occurence of 'o' in string s


char *res = strchr(s, 'o');

if (res != NULL)
printf("Character found at: %ld index", res - s);
else
printf("Character not found\n");
return 0;
}

Output
Character found at: 4 index
ix)strrev()
The strrev() function is used find the reverse of a given string

Example:
#include <stdio.h>
#include <string.h>

int main() {
char s[] = "Hello";
printf(“%s”,,strrev(s));

Output
olleH

Submit Assignment -I on or before 10.03.2025

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy