C PROGRAMMING
Sachin Dane
C language is a general purpose and structured programming
language developed by 'Dennis Ritchie' at AT &T's Bell
Laboratories in the 1972s in USA.
It is also called as 'Procedure oriented programming
language.'
C is not specially designed for specific applications areas
like COBOL (Common Business-Oriented Language) or
FORTRAN (Formula Translation).
It is well suited for business and scientific applications.
It has some various features like control structures,
looping statements, arrays, macros required for these
applications.
The C language has following numerous features as:
Portability
Flexibility
Effectiveness and efficiency
Reliability
Interactivity
Execution of C Program :
C program executes in following 4 (four steps).
1.Creating a program :
An editor like notepad or WordPad is used to create a C program.
This file contains a source code which consists of executable code.
The file should be saved as '*.c' extension only.
2.Compiling the program :
The next step is to compile the program. The code is compiled by using
compiler.
Compiler converts executable code to binary code i.e. object code.
3.Linking a program to library :
The object code of a program is linked with libraries that are needed for
execution of a program.
The linker is used to link the program with libraries.
It creates a file with '*.exe' extension.
4.Execution of program :
The final executable file is then run by dos command prompt or by any
other software.
Year of
Establishment
Language Name
Developed By
1960
ALGOL-60
Cambridge
University
1963
CPL (Combined
Programming
Language)
Cambridge
University
1967
BCPL (Basic
Combined
Programming
Language)
Martin Richard at
Cambridge
University
1970
Ken Thompson at AT
& T's Bell
Laboratories.
1972
Dennis Ritchie at AT
& T' Bell Laboratory.
General form of c program
Document Section
Document Section
Section (File)
LinksLinks
Section (File)
Definition
Section
Definition
Section
Global variable declaration Section
Global
variable declaration
void main()
Section
{
voidVariable
main()declaration section
Function declaration section
{
executable statements;
Variable
declaration section
}
executable
statements;
Function definition
1
--------------------}
--------------------Function
definition 1
Function definition n
--------------------where,
--------------------Function definition n
where,
Document Section : It consists of set of comment lines which include name
of a program, author name, creation date and other information.
Links Section (File) : It is used to link the required system libraries or
header files to excute a program.
Definition Section : It is used to define or set values to variables.
Global variable declaration Section : It is used to declare global or public
variable.
void main() : Used to start of actual C program. It includes two parts as
declaration part and executable part.
Variable declaration section : Used to declare private variable.
Then, executable statements are placed for execution.
Function definition section : Used to define functions which are to be
called from main().
VARIABLES AND KEYWORDS
Character Set :
1.
2.
3.
4.
A character refers to the digit, alphabet or special symbol used to data
representation.
Alphabets :
A-Z, a-z
Digits :
0-9
Special Characters : ~ ! @ # $ % ^ & * ( ) _ + { } [ ] - < > , . / ? \ | : ; " '
White Spaces :
Horizontal tab, Carriage return, New line
. Identifier :
identifier is the name of a variable that is made up from combination of
alphabets, digits and underscore.
. Variable :
It is a data name which is used to store data and may change during program
execution. It is opposite to constant. Variable name is a name given to
memory cells location of a computer where data is stored.
* Rules for variables:
First character should be letter or alphabet.
Keywords are not allowed to use as a variable name.
White space is not allowed.
C is case sensitive i.e. UPPER and lower case are significant.
Only underscore, special symbol is allowed between two characters.
Keywords :
Keywords are the system defined identifiers.
All keywords have fixed meanings that do not change.
White spaces are not allowed in keywords.
Keyword may not be used as an identifier.
It is strongly recommended that keywords should be in lower case
letters.
There are totally 32(Thirty Two) keywords used in a C programming.
int
float
double
long
short
signed
unsigned
const
if
else
switch
break
default
do
while
for
register
extern
static
struct
typedef
enum
return
sizeof
goto
union
auto
case
void
char
continue
volatile
Escape Sequence Characters (Backslash Character Constants) in C:
C supports some special escape sequence characters that are used to do special tasks.
Character Constant
Meaning
\n
New line (Line break)
\b
Backspace
\t
Horizontal Tab
\f
Form feed
\a
Alert (alerts a bell)
\r
Carriage Return
\v
Vertical Tab
\?
Question Mark
\'
Single Quote
\''
Double Quote
\\
Backslash
\0
Null
Constants in C
A constant is an entity that doesn't change during the execution of a
program.
Syntax: const data type var_name=expression;
Ex: const float pi=3.147
Followings are the different types of constants :
1. Real Constant :
It must have a decimal point which may be positive or negative.
Example:
+194.143, -416.41
2. Integer Constant :
It should not contain a decimal place.
It can be positive or negative.
Example:
1990, 194, -394
3. Character Constant :
It is a single alphabet or a digit or a special symbol enclosed in a single quote.
Maximum length of a character constant is 1.
Example:
'T', '9', '$'
4. String Constant :
It may contain letters, digits, special characters and blank space.
Example:
Hello friends welcome"
Data Types in C :
"Data type can be defined as the type of data of variable or constant store."
Followings are the most commonly used data types in C.
Keyword
Format Specifier
Size
Data Range
char
%c
1 Byte
-128 to +127
unsigned char
<-- -- >
8 Bytes
0 to 255
int
%d
2 Bytes
-32768 to
+32767
long int
%ld
4 Bytes
-231 to +231
unsigned int
%u
2 Bytes
0 to 65535
4 Bytes
-3.4e38 to
+3.4e38
8 Bytes
-1.7e38 to
+1.7e38
float
double
%f
%lf
-3.4e38 to
Operators in C :
"Operator is a symbol that is used to perform operations.
Followings are the most commonly used data types in C.
Operator Name
Operators
Assignment
Arithmetic
+ , - , *, /, %
Logical
&&, ||, !
Relational
<, >, <=, >=, ==, !=
Shorthand
+=, -=, *=, /=, %=
Unary
++, --
Conditional
Y=(x>9)? 100 :200 ;
Bitwise
&, |, ^, <<, >>, ~
Conditional Operator (?:)
The conditional operator ?: is a ternary operator. This means that it takes in
three
arguments that together form a conditional expression.
Syntax:
exp1?exp2:exp3
Where in exp1 is a boolean expression whose result must either be true or false.
If exp1 is true, exp2 is the value returned. If it is false, then exp3 is returned.
For example, given the code,
public class ConditionalOperator
{
public static void main( String[] args ){
String status = "";
int grade = 80;
//get status of the student
status = (grade >= 60)?"Passed":"Fail";
//print status
System.out.println( status );
}
}
The output of this program will be,
Passed
Here is the flowchart of how ?: works,
Increment and Decrement operators
Java includes a unary increment operator (++) and decrement
operator (--).
Increment and decrement operators increase and decrease a value
stored in a number variable by 1.
For example, the expression,
count = count + 1; //increment the value of count by 1
is equivalent to,
count++;
Operator Use
Description
++
op++
Increments op by 1; evaluates to
the value of op before it was incremented
++
++op
Increments op by 1;evaluates to
the value of op after it was incremented
-op-Decrements op by 1;evaluates to
the value of op before it was decremented
---op
Decrements op by 1;evaluates to
the value of op after it was decremented
For example,
int i = 10,
int j = 3;
int k = 0;
k = ++j + i;
//will result to k = 4+10 = 14
Input output statements in C
printf(
msg );
Scanf(format specifier ,&var_name );
printf(format specifier,var_name);
printf(msg format specifier,var_name);
Decision Making Statements / Conditional Statements :
C program executes program sequentially. Sometimes, a program requires
checking of certain conditions in program execution.
Followings are the different conditional statements used in C.
If Statement
If-Else Statement
Nested If-Else Statement
Switch Case
If Statement :
This is a conditional statement used in C to check condition or to
control the flow of execution of statements.
Syntax:
if (condition)
{
statements;
}
In above syntax, the condition is checked first. If it is true, then
the program control flow goes inside the braces and executes the
block of statements associated with it. If it returns false, then
program skips the braces.
If-Else Statement :
This is also one of the most useful conditional statement used in C to
check conditions.
Syntax:
if(condition)
{
true statements;
}
else
{
false statements;
}
In above syntax, the condition is checked first. If it is true, then
the program control flow goes inside the braces and executes the
block of statements associated with it. If it returns false, then it
executes the else part of a program.
Nested If-Else Statement :
It is a conditional statement which is used when we want to check more than 1
conditions at a time in a same program. The conditions are executed from top to
bottom checking each condition whether it meets the conditional criteria or not.
Syntax: if(condition)
{
if(condition)
{
statements;
}
else
{
statements;
}
}
else
{
statements;
}
In above syntax, the condition is checked first. If it is true, then the program
control flow goes inside the braces and again checks the next condition. If it is
true then it executes the block of statements associated with it else executes
else part.
Switch case Statement :
This is a multiple or multiway branching decision making statement.
When we use nested if-else statement to check more than 1 conditions then the
complexity of a program increases in case of a lot of conditions. So to overcome
this problem, C provides 'switch case'.
Switch case checks the value of a expression against a case values, if condition
matches the case values then the control is transferred to that point.
Syntax: switch(expression)
{
case expr1:
statements;
break;
case expr2:
statements;
break;
.
.
case expr N:
statements;
break;
default:
Statements;
break;
}
In this syntax,
switch, case,
break are
keywords.
expr1, expr2 are
known as 'case
labels.'
Break statement
causes an exit
from switch
statement.
Default case is
optional case.
When neither any
match found, it
executes
Looping Statements / Iterative Statements :
'A loop' is a part of code of a program which is executed
repeatedly.
A loop is used using condition. The repetition is done until
condition becomes condition true.
A loop declaration and execution can be done in following ways.
Check condition to start a loop
Initialize loop with declaring a variable.
Executing statements inside loop.
Increment or decrement of value of a variable.
* Types of looping statements :
Basically, the types of looping statements depends on the
condition checking mode.
Condition checking can be made in two ways as :
Before loop and after loop.
So, there are 2(two) types of looping statements.
Entry controlled loop
Exit controlled loop
1. Entry controlled loop :
In such type of loop, the test condition is checked
first before the loop is executed.
Some common examples of this looping statements
are :
while loop
for loop
2. Exit controlled loop :
In such type of loop, the loop is executed first. Then
condition is checked after block of statements are
executed.
The loop executed atleast one time compulsorily.
Some common example of this looping statement is :
do-while loop
While loop :
This is an entry controlled looping statement. It is used to
repeat a block of statements until condition becomes true.
Syntax:
while(condition)
{
statements;
increment/decrement;
}
In above syntax, the condition is checked first. If it is true,
then the program control flow goes inside the loop and
executes the block of statements associated with it. At the
end of loop increment or decrement is done to change in
variable value. This process continues until test condition
satisfies.
Do-While loop :
This is an exit controlled looping statement.
Sometimes, there is need to execute a block of statements first
then to check condition. At that time such type of a loop is used.
In this, block of statements are executed first and then
condition is checked.
Syntax:
do
{
statements;
(increment/decrement);
}
while(condition);
In above syntax, the first the block of statements are executed.
At the end of loop, while statement is executed. If the resultant
condition is true then program control goes to evaluate the body
of a loop once again. This process continues till condition becomes
true. When it becomes false, then the loop terminates.
For loop :
This is an entry controlled looping statement.
In this loop structure, more than one variable can be initialized.
One of the most important feature of this loop is that the three
actions can be taken at a time like variable initialization, condition
checking and increment/decrement.
Syntax:
for(initialization; test-condition; incre/decre)
{
statements;
}
Features :
More concise
Easy to use
Highly flexible
More than one variable can be initialized.
More than one increments can be applied.
More than two conditions can be used.
Break Statement :
Sometimes, it is necessary to exit immediately from a loop as soon as the
condition is satisfied.
When break statement is used inside a loop, then it can cause to terminate from
a loop. The statements after break statement are skipped.
Continue Statement :
Sometimes, it is required to skip a part of a body of loop under specific
conditions. So, C supports 'continue' statement to overcome this problem.
The working structure of 'continue' is similar as that of that break statement
but difference is that it cannot terminate the loop. Continue statement simply
skips statements and continues next iteration.
Syntax : break;
Syntax : continue;
While(condition)
{
- - - - - - - - - break;
- - - - }
While(condition)
{
- - - - - - - - - Continue;
- - - - - - }
Goto Statement :
It is a well known as 'jumping statement.' It is primarily used to transfer
the control of execution to any place in a program. It is useful to provide
branching within a loop.
When the loops are deeply nested at that if an error occurs then it is
difficult to get exited from such loops. Simple break statement cannot work
here properly. In this situations, goto statement is used.
Syntax : goto [expr];
While(condition)
{
- - - - - - - - - goto label;
- - - - label:
}
While(condition)
{
- - - - label:
- - - - - - goto label;
- - }
Functions in C :
The function is a self contained block of statements which performs a coherent
task of a same kind.
Types of functions :
Built in Functions
User Defined Functions
1. Built in Functions : These functions are also called as 'library
functions'. These functions are provided by system. These functions are
stored in library files.
e.g.
scanf()
printf()
strcpy()
strlwr()
strcmp()
strlen()
strcat()
2.User Defined Functions :
The functions which are created by user for program are known as 'User
defined functions'.
Advantages :
It is easy to use, It reduces the size of a program.
Debugging is more suitable for programs.
It is easy to understand the actual logic of a program.
Highly suited in case of large programs.
By using functions in a program, it is possible to construct
modular and structured programs.
Syntax:
// Function definition
<return_type> <function_name>(argu_list);
void main()
{
// Function Call
<function_name>(<arguments>);
}
// Function declaration
<return_type><function_name>(<argu_list>)
{
<function_body>;
}
FUNCTION TYPES:
1) Function with No arguments and No return value
2) Function with arguments but No return value
3) Function with No arguments but Returns a value
4) Function with arguments and return values
5) Function with multiple return values
In this ex. a & b are
actual arguments &
x is formal
argument
Some Points about functions:
A function cannot be defined within another function.
All function definitions must be disjoint.
Nested function calls are allowed.
A calls B, B calls C, C calls D, etc.
The function called last will be the first to return.
A function can also call itself, either directly or in a cycle.
A calls B, B calls C, C calls back A.
Called recursive call or recursion.
Calling Functions :Call by value and call by reference
Used when invoking functions
Call by Value:
Copy of argument pass to a function
Changes in function do not effect
original
Call by reference:
Passes original arguments to a function
Changes in function effect original
Recursion
A process by which a function calls itself repeatedly.
Either directly.
X calls X.
Or cyclically in a chain.
X calls Y, and Y calls X.
Used for repetitive computations in which each action is stated in
terms of a previous result.
fact(n) = n * fact (n-1)
For a problem to be written in recursive form, two conditions are
to be satisfied:
It should be possible to express the problem in
recursive form.
The problem statement must include a stopping
condition
fact(n) = 1, if n = 0
= n * fact(n-1), if n > 0
More example on recursion:
GCD:
gcd(m, m) = m
Gcd(m, n) = gcd(m-n, n), if m > n
gcd(m, n) = gcd(n, n-m), if m < n
Fibonacci
fib (0)
fib (1)
fib (n)
series (1,1,2,3,5,8,13,21,.)
= 1
= 1
= fib (n-1) + fib (n-2), if n > 1
Mechanism of Execution:
-When a recursive program is executed, the recursive
function calls are not executed immediately.
They are kept aside (on a stack) until the stopping
condition is encountered.
The function calls are then executed in reverse order.
Storage Class :
'Storage' refers to the scope of a variable and memory allocated
by compiler to store that variable. Scope of a variable is the
boundary within which a variable can be used. Storage class defines
the the scope and lifetime of a variable.
Functions of storage class :
To determine the location of a variable where it is stored ?
Set initial value of a variable or if not specified then setting it
to default value.
Defining scope of a variable.
To determine the life of a variable.
Types of Storage Classes :
Storage classes are categorized in 4 (four) types as,
1.
2.
3.
4.
Automatic storage class
Register storage class
Static storage class
External storage class
Automatic Storage Class :
Keyword : auto
Storage Location : Main memory
Initial Value : Garbage Value
Life : Control remains in a block where it is defined.
Scope : Local to the block in which variable is declared.
Syntax : auto [data_type] [variable_name];
Example : auto int a;
Register Storage Class :
Keyword : register
Storage Location : CPU Register
Initial Value : Garbage
Life : Local to the block in which variable is
declared.
Scope : Local to the block.
Syntax : register [data_type] [variable_name];
Example : register int a;
Static Storage Class :
Keyword : static
Storage Location : Main memory
Initial Value : Zero and can be initialize once only.
Life : depends on function calls and the whole application or program.
Scope : Local to the block.
Syntax : static [data_type] [variable_name];
Example : static int a;
External Storage Class :
Keyword : extern
Storage Location : Main memory
Initial Value : Zero
Life : Until the program ends.
Scope : Global to the program.
Syntax : extern [data_type] [variable_name];
Example : extern int a;
Array :
Array is a fixed sized sequenced collection of the elements of the same
data type .
Types of an Array :
1) Single / One Dimensional Array
2) Two Dimensional Array
. Single / One Dimensional Array :
The array which is used to represent and store data in a linear form is
called as 'single or one dimensional array.
Syntax: <data-type> <array_name> [size];
Memory Allocation:
A[i]
A[0]
A[1]
A[2]
A[n]
element
12
1000
1002
1004
addres
s
Two Dimensional Array :
The array which is used to represent and store data in a tabular form is
called as 'two dimensional array.' Such type of array specially used to
represent data in a matrix form.
The following syntax is used to represent two dimensional array.
Syntax: <data-type> <array_name> [row_size][column_size];
Example: int a[3][3];
It is also called as 'multidimensional array.'
i
row
a[0][0]
a[0][1]
a[0][2]
a[1][0]
a[1][1]
a[1][2]
a[2][0]
a[2][1]
a[2][2]
a[i][j]
Memory allocation for two dimensional array
Limitations of two dimensional array :
We cannot delete any element from an array.
If we don't know that how many elements have to be stored in a memory
in advance, then there will be memory wastage if large array size is
specified.
Structure
Structure is user defined data type which is used to store heterogeneous
data under unique name. Keyword 'struct' is used to declare structure.
The variables which are declared inside the structure are called as
'members of structure'.
Syntax:
struct structure_nm
{
<data-type> element 1;
<data-type> element 2;
-------------------<data-type> element n;
}struct_var;
* Accessing Structure Members :
Structure members can be accessed using member operator '.' .
It is also called as 'dot operator' or 'period operator'.
structure_var.member;
Structures within Structures (Nested Structures) :
Structures can be used as structures within structures. It is
also called as 'nesting of structures'.
Syntax:
struct structure_nm
{
<data-type> element 1;
<data-type> element 2;
-------------------<data-type> element n;
struct structure_nm {
<data-type> element 1;
<data-type> element 2;
--------------------<data-type> element n;
}inner_struct_var;
}outer_struct_var;
Union
Union is user defined data type used to stored data under unique variable
name at single memory location.
Syntax of union is similar to structure. But the major difference
between structure and union is 'storage.' In structures, each member
has its own storage location, whereas all the members of union use the
same location. Union contains many members of different types, it can
handle only one member at a time.
Syntax:
union union_name
{
<data-type> element 1;
<data-type> element 2;
<data-type> element 3;
}union_variable;
Example:
union techno
{
int comp_id;
char nm;
float sal;
}tch;
Memory Allocation
To access union members, we
can use the following syntax.
tch.comp_id
tch.nm
tch.sal
POINTER
Pointer is a variable which holds the memory address of another
variable. Pointers are represented by '*'. It is a derive data type in
C. Pointer returns the value of stored address.
Syntax: <data_type> *pointer_name;
int *tot;
int tot = 95;
In above syntax,
* = variable pointer_name is a pointer variable.
pointer_name requires memory location
pointer_name points to a variable of type data type.
Features of Pointer :
*
*
*
*
Pointer variable should have prefix '*'.
Combination of data types is not allowed.
Pointers are more effective and useful in handling arrays.
It can also be used to return multiple values from a function using
function arguments.
* It supports dynamic memory management.
* It reduces complexity and length of a program.
* It helps to improve execution speed that results in reducing program
String Handling in C
String :
A string is a collection of characters. Strings are always
enlosed in double quotes as "string_constant".
Strings are used in string handling operations such as,
Counting the length of a string.
Comparing two strings.
Copying one string to another.
Converting lower case string to upper case.
Converting upper case string to lower case.
Joining two strings.
Reversing string.
Declaration
Syntax: char string_nm[size];
Example: char name[50];
String Structure :
When compiler assigns string to character array then it automatically
supplies null character ('\0') at the end of string.
Thus, size of string = original length of string + 1.
char name[7]; name = "TECHNO"
Read Strings :
To read a string, we can use scanf() function with format specifier %s.
Write Strings :
char name[50];
scanf("%s",name);
To write a string, we can use printf() function with format specifier %s.
char name[50]; scanf("%s",name);
printf("%s",name);
String handling functions:
Function Name
Description
n=strlen (s1)
Returns the length of a string.
strlwr (s1)
Returns upper case letter to lower case.
strupr (s1)
Returns lower case letter to upper case.
strcat (s1,s2)
Concatenates two string.
strcmp (s1,s2)
Compares two strings.
strrev (s1)
Returns length of a string.
strcpy (s1,s2)
Copies a string from source to destination.
File handling in C
In C we use FILE * to represent a pointer to a file.
fopen is used to open a file. It returns the special value NULL to indicate
that it couldn't open the file.
FILE *fptr;
char filename[]= "file2.dat";
fptr= fopen(filename,"w");
if (fptr== NULL)
{
printf(ERROR IN FILE
CREATION);
/* DO SOMETHING */
}
Modes for opening files
The second argument of fopen is the mode in which we open
the file.
"r"opens a file for reading
"w"creates a file for writing -and writes over all previous
contents (deletes the file so be careful!)
"a"opens a file for appending -writing on the end of the
file
rbread binary file (raw bytes)
wbwrite binary file
The exit() function
Sometimes error checking means we want an
"emergency exit" from a program. We want it to stop
dead.
In main we can use "return" to stop.
In functions we can use exit to do this.
Exit is part of the stdlib.h library
exit(-1);
in a function is exactly the same as
return -1;
in the main routine
Writing to a file using fprintf( ):
fprintf( ) works just like printf and sprintf except that
its first argument is a file pointer.
FILE *fptr;
fptr= fopen("file.dat","w");
/* Check it's open */
fprintf(fptr,"Hello World!\n");
FILE *fptr;
fptr= fopen("file.dat","w");
/* Check it's open */
fprintf(fptr,"Hello World!\n");
Reading Data Using fscanf( )
input.dat
We also read data from a file using fscanf( ).
FILE *fptr;
fptr= fopen(input.dat,r);
/* Check it's open */
if (fptr==NULL)
{
printf(Error in opening file \n);
}
fscanf(fptr,%d%d,&x,&y);
20 30
x=20
y=30
Reading lines from a file using fgets( )
We can read a string using fgets( ).
fgets( ) takes 3 arguments, a string, a maximum
number of characters to read and a file pointer.
It returns NULL if there is an error.
FILE *fptr;
char line [1000];
/* Open file and check it is open */
while (fgets(line,1000,fptr)!= NULL)
{
printf("Read line %s\n",line);
}
Closing a file
We can close a file simply using fclose( )and the file pointer.
FILE *fptr;
char filename[]= "myfile.dat";
fptr= fopen(filename,"w");
Opening
if (fptr== NULL)
{
printf("Cannot open file to write!\n");
exit(-1);
}
fprintf(fptr,"Hello World of filing!\n");
Access
fclose(fptr);
Closing
Three special streams
Three special file streams are defined in the <stdio.h> header
stdin reads input from the keyboard
stdout send output to the screen
stderr prints errors to an error device
screen)
Ex:
fprintf(stdout,"Hello World!\n");
(usually also the
Input File & Output File redirection
One may redirect the input and output files to other files
(other than stdinand stdout).
Usage: Suppose the executable file is a.out
$./a.out <in.dat>out.dat
15
in.dat
Give value of i Value of i=15
No error: But an example to show error
message
out.dat
Display screen
Reading and Writing a character
A character reading/writing is equivalent to reading/writing a byte.
intgetchar( );
intfgetc(FILE *fp);
intputchar(int c);
intfputc(intc, FILE *fp);
Example:
char c;
c=getchar( );
putchar(c);
Program use of getchar() and putchar():
#include<stdio.h>
main()
{
int c;
printf("Type text and press return to see it again \n");
printf("For exiting press <CTRL D> \n");
while((c=getchar( ))!=EOF)
putchar(c);
}
Command Line Arguments:
Command line arguments may be passed by specifying them under main( ).
int main(int argc, char *argv[ ]);
Argument
count
Array of Strings as
command line
arguments including the
command itself.
Example: Reading command line arguments
#include<stdio.h>
#include<string.h>
int main(int argc,char *argv[])
{
FILE *ifp,*ofp;
int i,c;
char src_file[100],dst_file[100];
if(argc!=3)
{
printf("Usage:./a.out <src_file> <dst_file> \n");
exit(0);
}
Else
{
strcpy(src_file,argv[1]);
strcpy(dst_file,argv[2]);
}
./a.out s.dat d.dat
argc=3
./a.out
argv
s.dat
d.dat
if((ifp=fopen(src_file,"r"))==N
ULL)
{ printf("File does not
exist.\n");
exit(0);
}
if((ofp=fopen(dst_file,"w"))==
NULL)
{
printf("File not created.\n");
exit(0);
}
while((c=getc(ifp))!=EOF)
{
putc(c,ofp);
}
fclose(ifp);
fclose(ofp);
}
prg1
#include <stdio.h>
#include <conio.h>
void main()
{
clrscr();
printf("\n My first program in C !");
getch();
}
Thank You