STUDY ON UNIX
Ex No: 1
An operating system is the software component of the computer system that is responsible for
the management and coordination of activities and the sharing the limited resources effectively. The
figure 1 shows the layered structure of the system and where the operating system is located in it.
Operating systems offer a number of services to application programs and users. Users may also
interact with the operating system with some kind of software user interface (UI) like typing
commands by using command line interface (CLI) or using a graphical user interface (GUI). For
hand-held and desktop computers, the user interface is generally considered part of the operating
system. On large multi-user systems like UNIX and Unix-like systems, the user interface is generally
implemented as an application program that runs outside the operating system.
1
COMPUTER PRATICES LAB II 201
0
In single user operating system only one person can use the system at the same time. The
examples are DOS, Windows 95 and Windows 98.In multi-user operating system more than one
person can use the system at the same time. The examples are UNIX, LINUX and WINDOWS NT
etc.
The UNIX operating system is made up of two major parts, the kernel and the shell.
a) The kernel
The kernel of UNIX is the hub of the operating system: it allocates time and memory to programs and
handles the file store 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.
b) 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.
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.
2
COMPUTER PRATICES LAB II 201
0
These are the security for the system with many users.
1. User name
2. Password
Logging out is done if we want to quit. The command used for this is exit.
• UNIX is more flexible and can be installed on many different types of machines,
including mainframe computers, supercomputers and microcomputers.
• UNIX is more stable and does not go down as often as Windows does, therefore
requires less administration and maintenance.
• UNIX has greater built-in security and permissions features than Windows.
• UNIX possesses much greater processing power than Windows.
RESULT:
1. Date command
The date command can also be used with the following format specification.
3
COMPUTER PRATICES LAB II 201
0
2.who command
This command gives us the details of who all have logged into the UNIX system currently.
This tells us to when we had logged in and the system’s name for connection being used.
3.man command
4.pwd command
Format:$pwd
5.ls command
Format :$ls
ls -l :List files in login format. The files are displayed along with their mode,
number of links, owner of files, file size, modification date &time and
file name.
6.mkdir command
Example:$mkdir abc
7.rmdir command
Example:$rmdir abc
8.cd command
Format:$cd<directory name>
Example:$cd abc
9.cat command
Format:$cat[path]filename
$cat>abc
Ctrl d
10.cp command
11.ln command
This command is used to establish an additional file name for the same ordinary file.
12.mv command
13.rm command
This command is used to remove one or more files from a directory. This can be used to
delete all files as well as the directory.
Format: $rm[path]file
directory itself
14.echo command
This command is used to display whatever message we want to display on the screen.
Format:$echo”message”
15.grep command
The grep utility searches one or more files to see if any contain a specified string of
characters.
Format: grep’string’filename
16.diff command
The diff utility compares two files and displays a list of the difference between them. It
displays the list of actions to be taken to convert one file into another.
17.read command
This command is used in shell scripts.this command waits for the user to input the value of
the variable.
Format:$clear
$tput clear
6
COMPUTER PRATICES LAB II 201
0
19.exit command
Format:$exit
Exercises:
Oos OS
SUOS MUOS
7.Set the permission of the file3 to read write execute for user,read execute for
7
COMPUTER PRATICES LAB II 201
0
RESULT:
A Linux shell is a command language interpreter, the primary purpose of which is to translate the
command lines typed at the terminal into system actions. The shell itself is a program, through which
other programs are invoked
• A shell script is a file containing a list of commands to be executed by the Linux shell. shell
script provides the ability to create your own customized Linux commands
• Linux shell have sophisticated programming capabilities which makes shell script powerful
Linux tools
How to work with shell ?
Step1:
8
COMPUTER PRATICES LAB II 201
0
Where vi is the editor ,it will open a new window in which you can type the program you want
Step2:
After typing the program press ESC and : together then at the bottom of the vi screen you can see i.e.
prompt .In that type as wq which means write and quit i.e. the content what is typed will be written
and saved into that file that has been created
Step3:
Once wq is typed at the : prompt ,the prompt would change to $ symbol in which you have to do the
following
<file name> - is the name of the file for which the output is to be got
Basically to print a text in the your shell programs echo command is used
IF –THEN-ELSE CONSTRUCT
if [ condition]
then <action>
else
statements
fi (end of if)
WHILE
while <condition>
do
9
COMPUTER PRATICES LAB II 201
0
<statements>
Done
CASE
Case $<option> in
1) <statements>;;
2) <statements>;;
3) ..
4)
.
*) <error statement>;;
esac
For loop
For(( intitialization;condition;incremetation/decrementation))
10
COMPUTER PRATICES LAB II 201
0
Aim: To write a shell program to display the wishes based on the time.
Algorithm:
d=`date +%H`
echo $d
Result:
Thus the time was found and a wish was displayed using the shell program.
11
COMPUTER PRATICES LAB II 201
0
Algorithm:
read a
read b
if [ $a -gt $b ]
fi
Result:
Thus the bigger of 2 numbers was found using the shell program
12
COMPUTER PRATICES LAB II 201
0
Aim:
Algorithm:
read a
read b
read c
if [ $a -gt $b -a $a -gt $c ]
then
elif [ $b -gt $c ]
then
else
fi
Result:Thus the biggest of 3 numbers was found using the shell program.
13
COMPUTER PRATICES LAB II 201
0
Algorithm:
read s1
read s2
if [ $s1 == $s2 ]
then
else
fi
Result:
Ex no 3e Arithmetic Operations
Aim: To write a shell program to perform arithmetic operations using switch statement
Algorithm:
14
COMPUTER PRATICES LAB II 201
0
read a
read b
read n
case $n in
1) echo "addition" ;
c=`expr $a + $b `;
exit ;;
2) echo "subtraction" ;
c=`expr $a - $b `;
exit ;;
3) echo "multiplication" ;
c=`expr $a \* $b `;
exit ;;
4) echo "division" ;
c=`expr $a / $b `;
exit ;;
*) echo "Invalid" ;
esac;;
15
COMPUTER PRATICES LAB II 201
0
Result:
Thus the arithmetic operations were performed using the shell program.
Algorithm:
echo -----------------------
echo -----------------------
read n
sum=0
i=2
while [ $i -le $n ]
do
i=`expr $i + 2`
done
Result:Thus the sum of even numbers upto n was found using the shell program.
16
COMPUTER PRATICES LAB II 201
0
Algorithm:
echo --------------------------
echo --------------------------
read n
sum=0
i=0
while [ $i -le $n ]
do
i=`expr $i + 1`
done
Result:
Thus the sum of ‘ n ‘ natural numbers was found using the shell program
Algorithm:
17
COMPUTER PRATICES LAB II 201
0
3. Initialize i
4. Add a and b and assign to c
5. Print c
6. Assign the value of b to a and the value of c to b
7. Increment i by 1
8. Repeat the above steps until i is less than n
Program:
a=0
b=1
c=0
read n
i=3
echo $a
echo $b
for((i=0;$i<$n;i++))
c=` expr $a + $b `
echo $c
a=$b
b=$c
Result Thus the fibonacci series was generated using shell program .
Ex No: 4 VI EDITOR
The vi editor is available on almost all Unix systems. You can use vi from any type of
connection to UNIX because it does not depend on arrow keys and function keys: it uses the standard
alphabetic keys for commands. vi is short for visual editor; it displays a window into the file being
edited that shows 24 lines of text.
MODES:
18
COMPUTER PRATICES LAB II 201
0
a) Command mode
b) Insertion mode
c) Last Line mode
A) Command Mode:
The command mode is one which user is able to enter commands. The command
mode allows the entry of commands to manipulate text. These commands are usually one or two
characters long, and can be entered with few keystrokes.
B) Insertion Mode:
The insertion mode is one in which, the user can enter the data or edit the data. The
insert mode puts anything typed on the keyboard into the current file.
The Last line mode is one in which user is able to enter special commands.
STARTING VI EDITOR:
To start using vi, at the UNIX prompt type vi followed by a file name.
$vi newname
at the Unix $ prompt, where newname is the name you wish to give the new file. On the screen you
will see blank lines, each with a tilde at the left, and a line at the bottom giving the name and status of
the file:
Use vi to open an already existing file by typing vi filename where filename is the name of the
existing file. If the file is not in your current directory, you must use the full pathname.
ENTERING TEXT:
vi has two modes: command mode and insert mode. In command mode, the letters of the
keyboard perform editing functions (like moving the cursor, deleting text, and so on). In insert mode,
the letters you type form words and sentences. Unlike word processors, vi starts up in command
mode. To begin entering text in an empty file, you must change from command mode to insert mode.
To do this, type the letter i. You may see INSERT MODE at the bottom right of the screen, or nothing
may appear to change, but you are now in insert mode and can begin typing text. If you make a
19
COMPUTER PRATICES LAB II 201
0
mistake, pressing the Backspace or Delete key may or may not remove the error, depending on the
configuration of the software you are using to connect to the Login Service.
While editing, VI keeps the edited text in an area called work buffer. When editing is
finished, the user must write out the contents of the work buffer to disk file.
1. The ZZ (upper case) command can be used to write the newly entered text to the disk and
then end the editing session and returns the control to the shell.
2. To exit without saving the work, use :q! command
3. To quit after writing change to the disk file :wq command is used
4. To quit after replacing the old copy of the file with the new one, :x command is used.
COMMANDS:
a) Getting out
When we want to get out of the editor, switch to command mode(press ESC) if necessary,
then
:q Quit vi
20
COMPUTER PRATICES LAB II 201
0
b) Inserting Text
From command mode, these keystrokes switch you into insert mode with new text being
inserted.
c) Deleting Text
d0 Deletes from the cursor position till the beginning of the line
d$ Deletes from the cursor position till the end of the line
21
COMPUTER PRATICES LAB II 201
0
d) Moving Around
When in command mode we can use the arrow keys to move the cursor up,down,left,right. In
addition, these keystrokes will move the cursor:
From command mode, use these keystroke (or keystroke-combination) commands for the
described cut/copy/paste function:
22
COMPUTER PRATICES LAB II 201
0
p Move the text from temporary storage into the current position of cursor
Instead of using the “moving around” commands above, we can go directly forward or
backward to specified text using “/” and “?”
Replacing Text:
s Deletes the current character and inserts character until <ESC> is pressed
S Removes all characters on the current line and allows the user to enter data
Screen Manipulation:
The following commands allow the vi editor to move up and down several lines and to be
refreshed
23
COMPUTER PRATICES LAB II 201
0
Exercises
1. Create a file under the name vifile and enter the following text
An operating system is the software component of the computer system that is responsible for
the management and coordination of activities and the sharing the limited resources effectively.
4. Move the cursor to the top of screen, bottom of screen and middle of screen
5. Search for the word “system” and enter the following lines below it.
24
COMPUTER PRATICES LAB II 201
0
The kernel of UNIX is the hub of the operating system: it allocates time and memory to
programs and handles the file store and communications in response to system calls.
10. Copy the first three lines and paste it as 6 to 9th line
12. Search for the word “is” forward and in reverse direction.
RESULT:
C Programming on UNIX
Ex No: 5: Functions in C
Function:
A function is a complete and independent program, which is used (or invoked) by the main
program or other subprograms. A subprogram receives values called arguments from a calling
program, performs calculations and returns the results to the calling program.
Advantages of using functions:
There are many advantages in using functions in a program they are:
2. The length of the source program can be reduced by using functions at appropriate
places. This factor is critical with microcomputers where memory space is limited.
3. It is easy to locate and isolate a faulty function for further investigation.
4. A function may be used by many other programs this means that a c programmer can
build on what others have already done, instead of starting over from scratch.
25
COMPUTER PRATICES LAB II 201
0
5. A program can be used to avoid rewriting the same sequence of code at two or more
locations in a program. This is especially useful if the code involved is long or
complicated.
6. Programming teams does a large percentage of programming. If the program is
divided into subprograms, each subprogram can be written by one or two team members
of the team rather than having the whole team to work on the complex program
C supports the use of library functions and use defined functions. The library functions are used to
carry out a number of commonly used operations or calculations. The user-defined functions are
written by the programmer to carry out various individual tasks.
Function Definition:
argument declaration;
{
local variable declarations;
statements;
[return expression];
}
Example:
mul(int a,int b)
{
int y;
y=a*b;
return y;
}
Types of functions:
A function may belong to any one of the following categories:
1. Functions with no arguments and no return values.
2. Functions with arguments and no return values.
3. Functions with arguments and return values.
1. Functions with no arguments and no return values.
When a function has no arguments it does not receive any data from the calling function.
Similarly when it does not return value the calling function does not receive any data from the called
function. A function that does not return any value cannot be used in an expression it can be used only
as independent statement.
2. Functions with arguments but no return values:
The nature of data communication between the calling function and the arguments to the
called function and the called function does not return any values to the calling function.
3. Functions with arguments and return values:
The function of the type Arguments with return values will send arguments from the calling
function to the called function and expects the result to be returned back from the called function back
to the calling function.
Return value data type of function:
A C function returns a value of type int as the default data type when no other type is
specified explicitly. For example if function does all the calculations by using float values and if the
return statement such as return (sum); returns only the integer part of the sum. This is since we have
not specified any return type for the sum. There is the necessity in some cases it is important to
26
COMPUTER PRATICES LAB II 201
0
receive float or character or double data type. To enable a calling function to receive a non-integer
value from a called function we can do the two things:
1. The explicit type specifier corresponding to the data type required must be mentioned in the
function header. The general form of the function definition is
Type_specifier function_name (argument list)
Argumentdeclaration;
{
functionstatement;
}
The type specifier tells the compiler, the type of data the function is to return.
2. The called function must be declared at the start of the body in the calling function, like any
other variable. This is to tell the calling function the type of data the function is actually
returning. The program given below illustrates the transfer of a floating-point value between
functions done in a multiple function program.
Void functions:
The functions that do not return any values can be explicitly defined as void. This prevents
any accidental use of these functions in expressions.
Algorithm:
#include<stdio.h>
int i,t,j;
for(i=0;i<n;i++)
for(j=i+1;j<n;j++)
{
27
COMPUTER PRATICES LAB II 201
0
if(a[i]>a[j])
t=a[i];
a[i]=a[j];
a[j]=t;
for(i=0;i<n;i++)
printf("%d\n",a[i]);
main()
int i,a[20],n;
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
sort(a,n);
28
COMPUTER PRATICES LAB II 201
0
Result: Thus the program to sort ‘n’ numbers was executed and sorted array of elements was
obtained.
Aim
To write a C program to find whether the given string is a palindrome or not.
Algorithm
• Read a string
• Find the length of the string read.
• Reverse the string.
• Compare and check whether the given strings are equal.
• Set a flag value
• If the flag=1 then the given string is a palindrome.
• Otherwise, the given string is not a palindrome.
29
COMPUTER PRATICES LAB II 201
0
Program
#include<stdio.h>
char str[50];
int len=0,i=0,j,flag=1;
main()
{
printf("Enter a String:");
scanf("%s",str);
palindrome();
}
palindrome()
{
while(str[i++]!='\0')
len++;
for(i=0,j=(len-1);i<len/2;i++,j--)
{
if(str[j]!=str[i])
{
flag=0;
break;
}
}
if(flag==1)
printf("The given String is a Palindrome\n");
else
printf("The given String is not a Palindrome\n");
}
Result
Thus the C program to find whether the given string is a palindrome or not was written and
the output was verified.
Ex No: 6 Pointers
Introduction:
30
COMPUTER PRATICES LAB II 201
0
The syntax is as shown below. You start by specifying the type of data stored in the location
identified by the pointer. The asterisk tells the compiler that you are creating a pointer variable.
Finally you give the name of the variable.
Syntax:
datatype *variablename;
Example:
int *ptr;
float *string;
Address operator:
Once we declare a pointer variable we must point it to something we can do this by assigning
to the pointer the address of the variable you want to point as in the following example:
ptr=#
This places the address where num is stores into the variable ptr. If num is stored in memory
21260 addresses then the variable ptr has the value 21260.
Pointer expressions & pointer arithmetic:
Like other variables pointer variables can be used in expressions. For example if p1 and p2
are properly declared and initialized pointers, then the following statements are valid.
y=*p1**p2;
sum=sum+*p1;
Pointers and function:
The pointers are very much used in a function declaration. Sometimes only with a pointer a
complex function can be easily represented and success. The usage of the pointers in a function
definition may be classified into two groups.
1. Call by reference
2. Call by value
Call by value: When a function is invoked there will be a link established between the formal and
actual parameters. A temporary storage is created where the value of actual parameters is stored. The
formal parameters picks up its value from storage area the mechanism of data transfer between actual
and formal parameters allows the actual parameters mechanism of data transfer is referred as call by
value. The corresponding formal parameter represents a local variable in the called function. The
current value of corresponding actual parameter becomes the initial value of formal parameter. The
value of formal parameter may be changed in the body of the actual parameter. The value of formal
parameter may be changed in the body of the subprogram by assignment or input statements. This
will not change the value of actual parameters.
Call by Reference: When we pass address to a function the parameters receiving the address should
be pointers. The process of calling a function by using pointers to pass the address of the variable is
known as call by reference. The function, which is called by reference, can change the values of the
variable used in the call.
31
COMPUTER PRATICES LAB II 201
0
Algorithm:
#include<stdio.h>
int temp;
32
COMPUTER PRATICES LAB II 201
0
temp=*x;
*x=*y;
*y=temp;
main()
int a,b;
scanf("%d%d",&a,&b);
swap(&a,&b);
printf("a=%d\nb=%d",a,b);
printf("\n");
Result:Thus the program was executed and the two numbers were swapped using pointers.
Algorithm:
#include<stdio.h>
main()
33
COMPUTER PRATICES LAB II 201
0
int a[10];
int n,i,*p,sum=0;
p=a;
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for(i=0;i<n;i++)
sum=sum + *(p+i);
Result: Thus the program to find sum of ‘n’ numbers was found using C program.
C supports with memory management functions, which can be used to allocate and free
memory during the program execution. The following functions are used in c for purpose of memory
management.
Functio Task
n
malloc Allocates memory requests size of bytes and returns a pointer to the Ist byte of
allocated space
34
COMPUTER PRATICES LAB II 201
0
calloc Allocates space for an array of elements initializes them to zero and returns a
pointer to the memory
A block mf memory may be allocated using the function malloc. The malloc function reserves
a block of memory of specified size and returns a pointer of type void. This means that we can assign
it to any type of pointer. It takes the following form:
ptr=(cast-type*)malloc(byte-size);
where ptr is a pointer of type cast-type the malloc returns a pointer (of cast type) to an area of memory
with size byte-size.
Example:
x=(int*)malloc(100*sizeof(int));
On successful execution of this statement a memory equivalent to 100 times the area of int
bytes is reserved and the address of the first byte of memory allocated is assigned to the pointer x of
type int
Allocating multiple blocks of memory:
Calloc is another memory allocation function that is normally used to request multiple blocks
of storage each of the same size and then sets all bytes to zero. The general form of calloc is
ptr=(cast-type*) calloc(n,elem-size);
The above statement allocates contiguous space for n blocks each size of elements size bytes.
All bytes are initialized to zero and a pointer to the first byte of the allocated region is returned. If
there is not enough space a null pointer is returned.
35
COMPUTER PRATICES LAB II 201
0
Compile time storage of a variable is allocated and released by the system in accordance with
its storage class. With the dynamic runtime allocation, it is our responsibility to release the space
when it is not required. The release of storage space becomes important when the storage is limited.
When the data stored in a block of memory is not then the allocated block of memory for future use
can be released , using the free function.
free(ptr);
The memory allocated by using calloc or malloc might be insufficient or excess sometimes in
both the situations we can change the memory size already allocated with the help of the function
realloc. This process is called reallocation of memory. The general statement of reallocation of
memory is:
ptr=realloc(ptr,newsize);
This function allocates new memory space of size newsize to the pointer variable ptr and returns a
pointer to the first byte of the memory block. The allocated new block may be or may not be at the
same region.
Algorithm:
#include<stdio.h>
#include<malloc.h>
#define s 40
main()
char *s1,*s2,*s3,c;
int i,j,k;
36
COMPUTER PRATICES LAB II 201
0
s1=(char*)malloc(s*sizeof(char));
s2=(char*)malloc(s*sizeof(char));
s3=(char*)malloc(2*s*sizeof(char));
scanf("%s",s1);
scanf("%s",s2);
i=0;
while((c=*(s1+i))!='\0')
*(s3+i)=c;
i=i+1;
k=0;
while((c=*(s2+k))!='\0')
s3[i+k]=c;
k=k+1;
printf("%s\n",s3);
Result:
Algorithm:
Program:
#include<stdio.h>
#include<stdlib.h>
main()
char *p;
p=(char *)malloc(6);
strcpy(p,"MADRAS");
printf("Memory contains:%s\n",p);
38
COMPUTER PRATICES LAB II 201
0
p=(char *)realloc(p,7);
strcpy(p,"CHENNAI");
free(p);
Result:
Thus the program to alter the allocated memory was executed and the output was verified.
Ex No: 8 Files in C
Files:
File operations:
C supports a number of functions that have the ability to perform basic file operations, which
include:
1. Naming a file
2. Opening a file
3. Reading from a file
4. Writing data into a file
5. Closing a file
• Real life situations involve large volume of data and in such cases, the console oriented I/O
operations pose two major problems
• It becomes cumbersome and time consuming to handle large volumes of data through
terminals.
• The entire data is lost when either the program is terminated or computer is turned off
therefore it is necessary to have more flexible approach where data can be stored on the disks
and read whenever necessary, without destroying the data. This method employs the concept
of files to store data.
File operation functions in C:
39
COMPUTER PRATICES LAB II 201
0
In order to store data in a file into the secondary memory, certain things must be specified
about the file to the operating system. They include the fielname, data structure, and purpose. The
general format of the function used for opening a file is
FILE *fp;
fp=fopen(“filename”,”mode”);
The first statement declares the variable fp as a pointer to the data type FILE. As stated
earlier, File is a structure that is defined in the I/O Library. The second statement opens the file named
filename and assigns an identifier to the FILE type pointer fp. This pointer, which contains all the
40
COMPUTER PRATICES LAB II 201
0
information about the file, is subsequently used as a communication link between the system and the
program. The second statement also specifies the purpose of opening the file. The mode does this job.
R open the file for read only.
W opens the file for writing only.
A open the file for appending data to it.
In these statements the p1 and p2 are created and assigned to open the files data and results
respectively the file data is opened for reading and result is opened for writing. In case the results file
already exists, its contents are deleted and the files are opened as a new file. If data file does not exist
error will occur.
Closing a file:
The input output library supports the function to close a file; it is in the following format.
fclose(file_pointer);
A file must be closed as soon as all operations on it have been completed. This would close
the file associated with the file pointer.
….
FILE *p1 *p2;
p1=fopen (“Input”,”w”);
p2=fopen (“Output”,”r”);
…..
…..
fclose(p1);
fclose(p2);
The above program opens two files and closes them after all operations on them are
completed, once a file is closed its file pointer can be reversed on other file.
getc and putc functions:
The getc and putc functions are analogous to getchar and putchar functions and handle one
character at a time. The putc function writes the character contained in character variable c to the file
associated with the pointer fp1. ex putc(c,fp1); similarly getc function is used to read a character from
a file that has been open in read mode. c=getc(fp2).
41
COMPUTER PRATICES LAB II 201
0
These are integer-oriented functions. They are similar to get c and putc functions and are used
to read and write integer values. These functions would be usefull when we deal with only integer
data. The general forms of getw and putw are:
putw(integer,fp);
getw(fp);
The fprintf and scanf functions are identical to printf and scanf functions except that they
work on files. The first argument of theses functions is a file pointer, which specifies the file to be
used. The general form of fprintf is
fprintf(fp,”control string”, list);
Where fp id a file pointer associated with a file that has been opened for writing. The control
string is file output specifications list may include variable, constant and string.
fprintf(f1,%s%d%f”,name,age,7.5);
Here name is an array variable of type char and age is an int variable .The general format of
fscanf is
fscanf(fp,”controlstring”,list);
This statement would cause the reading of items in the control string.
Example:
fscanf(f2,”5s%d”,item,&quantity”);
Like scanf, fscanf also returns the number of items that are successfully read.
Sometimes it is required to access only a particular part of the and not the complete file. This
can be accomplished by using the fseek function.
fseek function:
This function is used to move the file position to a desired location within the file. Fileptr
is a pointer to the file concerned. Offset is a number or variable of type long, and position in an
integer number. Offset specifies the number of positions (bytes) to be moved from the location
specified bt the position. The position can take the 3 values.
Value Meaning
0 Beginning of the file
1 Current file
2 End of the file
42
COMPUTER PRATICES LAB II 201
0
Aim
To write a C program to display the contents available in a file.
Algorithm
1. Read the file to be displayed.
2. The file to be read is opened in read mode.
3. Read the contents of the file character by character.
4. Print the characters read.
5. Close the file when all its contents are read.
Program
#include<stdio.h>
main()
FILE *fopen(),*fp;
int c;
fp=fopen("Read_File","r");
c=getc(fp);
while(c!=EOF)
putchar(c);
c=getc(fp);
fclose(fp);
Result
Thus the C program to read the contents available in a file was written successfully and the
output was verified.
43
COMPUTER PRATICES LAB II 201
0
Aim
To write a C program to read the contents available in a file and to reverse it.
Algorithm
1. Read the file whose content is to be reversed in read mode.
2. Open another file in write mode in to which the reversed information is to be written.
3. Move the file pointer to the end of the file whose contents is to be reversed using the
function fseek().
4. Bring the position back to the last but one character in the file.
5. The function getc() is used to read the next character and after reading, the file
pointer is incremented to the next position.
6. The output thus obtained is displayed in the screen.
Program
#include<stdio.h>
main()
char ch;
FILE *fp1,*fp2;
fp1=fopen("Input_File","r");
fp2=fopen("Output_File","w");
fseek(fp1,0,2);
while(fseek(fp1,-2,1)==0)
ch=getc(fp1);
44
COMPUTER PRATICES LAB II 201
0
putchar(ch);
putc(ch,fp2);
Result
Thus the C program to reverse the contents available in a file was written successfully and the
output was verified.
To write a C program to find the transpose of a matrix and to write into a file.
Algorithm
1. Initialize a matrix.
2. Open a file write mode into which the transpose matrix is to be written.
3. Perform transpose of a matrix and write the contents into the opened file.
4. The transpose of the matrix is written into the file.
Program
#include<stdio.h>
main()
int i,j;
int matrix[2][3]={{1,2,3},{4,5,6}};
FILE *fp;
fp=fopen("matrix","w");
for(i=0;i<3;i++)
for(j=0;j<2;j++)
45
COMPUTER PRATICES LAB II 201
0
fprintf(fp,"\t%d\t",matrix[j][i]);
fprintf(fp,"\n");
Result
Thus the C program to write the transpose of a matrix into a file was written successfully and
the output was verified.
46