Home » C Programming

Category Archives: C Programming

Command Line Argument in C Programming

In a C programming often a situation may come where we want to pass the information into a program during the execution of program. These values are called Command Line Arguments(CLA).

“main()” function handles the command line argument.

Syntax:

int main( int argc, char *argv[] )
{

}

Here, argc refers to the number of arguments passed  and argv[] is a pointer array which points to each argument .

Note:  argv[0] - holds the name of the program

           argv[1]- holds the first command line argument, argv[2]- holds the second command line argument and and so on.

           If no argument is supplied, argc will be 1

Example: Write a program in a C to take one value from user during execution as a command line argument.

#include int main(int argc, char *argv[] ) { printf(“Program name is: %s = “, argv[0]); printf(“\n Command line argument is: %s”, argv[1]); return 0; }

Note: Suppose above program name is “CLA”.

Run this program as follows in Linux:

./CLA hello 

Here hello is a command line argument.

Run this program as follows in Windows from command line:

program.exe  hello

 Here hello is a command line argument.

Output:

Program name is: CLA
First argument is: hello

Example: Write a program in a C to take 4 value from user during execution as a command line argument.

OUTPUT

Note: Suppose above program name is “CLA”.

Run this program as follows in Linux:

./CLA  this is IT department

Here this is IT department are 4 command line argument.

OUTPUT

Program name : CLA
1st arg : this
2nd arg : is
3rd arg : IT
4th arg : department
5th arg : (null)

File handling programs in C Programming

Example : Write a C program to copy the contents of one file to another file.

OUTPUT

Example : Write a C program to appends the content of file at the end of another file.

Or

 Example : Write a C program to merge two files into third file.

Example: Write a C program to count spaces ,vowels, consonants, digits in a file .

Writing to a File in C Programming

To write on a file there are following  function available:

  1.  Function fputc() : function fputc() write individual characters at a time to the file. The syntax of this function is –

Syntax :

               int  fputc( int c,  FILE *fp );

Function fputc()  returns the written character written on success and  if there is an error it will return EOF (Emd of File).

  • Function fputs() :  function fputs() writes the string s’ to the output stream referenced by fp. The syntax of this function is –

Syntax :

               int fputs( const char *s, FILE *fp );

Function fputs()  returns the non-negative value  on success and  if there is an error it will return EOF (Emd of File).

  • Function fprintf(): Function fprintf()write a string into a file. The syntax of this function is –

Syntax :

int  fprintf(FILE  *fp,  const  char *format, …)

Example: Write a C program to write a single character into file using fputc() function in file handling.

OUTPUT

a
BOOK1.txt

 Example: Write a C program to write a string into a file using fputs() and fprintf() function in file handling.

OUTPUT

Hello  hii  how are you
I am aditya

Book1.txt

Description: When  we run the above program , it creates a new file Book1.txt in /c directory and writes two lines using fputs() and fprintf() functions.

Example : Write a C program to open a file, write in it and close the file.

  OUTPUT

i am aditya from it department

Book1.txt

Reading a File in C Programming

Reading a File

To read a  file there are following  function available:

  1. Function fgetc():  Function fgetc() is used to read a single character at a time from the input file. The syntax of this function is −

            Syntax :

               int fgetc( FILE * fp );

  • Functions fgets():  Functions fgets() is used to reads string from input file, one line at a time. The syntax of this function is –

Syntax :

               char *fgets( char *buf, int n, FILE *fp );

function fgets() copies the read string into the buffer buf and appending a null character to terminate the string.

Here “n” is a size of buffer.

*fp- is a file pointer.

If the function fgets() encounters a character ‘\n’  ( newline ) or the end of the file (            EOF ) before reading the maximum number of characters, then it will returns the characters read up to that point including the new line character.

  • Function fscan(): Function fscan() is also use to read strings from a file. The syntax of this function is –

Syntax :

            int fscanf(FILE *fp, const char *format, …) 

 Note: fscan() function stops reading after encountering the first space character in file.

Closing a File

The fclose() function is used to close an already opened file.  The syntax of this function is −

 Syntax :

int   fclose( FILE *fp );

Function fclose(-) returns zero if the file is successfully closed, or EOF if there is an error in closing the file.

Example:  Write a C program to show the use of fgets() and fscan() function using file handling.

Suppose we have a file Book.txt, that have following content

Hello  hii  how are you I am aditya

OUTPUT

Description:  fscanf() function read only “Hello” because after that, it encountered a space. fscan() function stops reading after encountering the first space character in file.

Function fgets() reads the remaining line till it encountered end of line. fgets() is  reads string from input file, one line at a time.

Finally, the last fgets() reads the second line completely.

Example: Write a C program to open a file, read a file and close file using file handling.

                                                Or

Example:  Write a program to show the use of  fgetc() function.

Note:  Used for  reads a single character from file. It returns EOF at the end of file.

OUTPUT

The content of the file “file1” will be printed.

File Handling in C Programming

A file represents a sequence of bytes and these file’s is used to store information. There are various different operations that we can be performed on a file are:

  1. Creation of a new file (fopen with attributes as “a” or “a+” or “w” or “w++”)
  2. Opening an existing file (fopen)
  3. Reading from file (fscanf or fgetc)
  4. Writing to a file (filePointerrintf or filePointeruts)
  5. Moving to a specific location in a file (fseek, rewind)
  6. Closing a file (fclose)

Functions for file handling

There are various predefined functions available for handle file. Some of them mentioned below:

Function Description
fopen() Used for opens new or existing file
fprintf() Used for write data into the file
fscanf() Used for reads data from the file
fputc() Used for writes a single character into the file
fgetc() Used for  reads a single character from file
fclose() Used for closes the file
fseek() sets the file pointer to given position
fputw() Used for writes an integer to file
fgetw() Used for  reads an integer from file
ftell() returns current position
rewind() sets the file pointer to the beginning of the file

Create or Open Files

We can create a new file or open an existing file by using fopen() function. To create a new file or open an existing file syntax is:

FILE   *fopen( const char * filename, const char * mode );

Here, filename is a string literal and use one of the following modes in the fopen() function if you are working with text file:-

File Mode Meaning of Mode
r opens a file in read mode. If the file does not exist, fopen() returns NULL.
w opens a file in write mode. If the file does not exist, fopen() returns NULL.
a opens a file in append mode ( Data is added to end of file). f the file does not exists, it will be created.
r+ opens a file in a both read and write mode. If the file does not exist, fopen() returns NULL.
w+ opens a file in both read and write mode. If the file exists, its contents are overwritten. If the file does not exist, it will be created.
a+ opens a file in both read and write mode. If the file does not exists, it will be created.

Arithmetic Operation With Pointer

In a C programming, we can also perform arithmetic operations with pointer. There are four arithmetic operators that can be performed with pointers:

  • Increment (++)
  • Decrement ( — )
  • Addition ( + )
  • Subtraction ( – )

 

Increment a Pointer

Example: Write a program in c language, to increments the variable pointer to access each succeeding element of the array.

OUTPUT

Array of pointers in C Programming

Example: Write a program to assign the address of array elements to pointer variable and print the array element with address.

OUTPUT

NULL Pointers in C Programming

A pointer that is assigned NULL is called a null pointer. We must initialize NULL pointer during variable declaration.

A null pointer refers to pointer variable that does not point to a valid address.

Generally NULL pointer is used when you do not have an exact address to be assigned.

OUTPUT

Pointer to Pointer in C Programming

In  C language, a pointer is an address. Normally, a pointer variable contains the address of a another variable. 

A pointer to a pointer is a chain of pointers. 

Or

Pointer to pointer means one pointer variable holds the address of another pointer variable.

Pointer to Pointer
Fig: Pointer to Pointer
Fig: Pointer to Pointer Example

Pointers in C Programming

In    programming, variable is used to hole the value & this variable stored in a memory.  Each variable has a address to identify where these variables actually stored in a memory.   

 In a C programming language, pointer is a variable which can hold the address of another variable.  

Accessing Address of Variable

In a system every memory location has its address & we can access the address using ampersand (&) operator.

This ampersand (&) operator  denotes an address in memory. 

Ex:  
int  i = 20;
char c = ‘a’;

In the above example, there are two variable i & c.

C Language Pointer explanation
Fig:Memory variable and address explanation using pointer

Integer variable “i” stores the value 10 at memory location 1024(for example) and character variable “c” stores the value ‘a’ at memory location 1026.

OUTPUT

If we want to print the address of variable ‘i and c’ then we need ampersand (&) operator  .

#include int main() { int i=20; int c=’a’; printf(“\n Address of variable i = %d”, &i ); printf(“\n Address of variable c= %d”, &c ); }

OUTPUT

Note: When you run this program, address are printed might be different.

Example: Write a program to print the address of the variable.

OUTPUT

Note: Each and every time when you run this program these variables stored in a different memory location.

Pointer Variable

pointer  variable is hold the address of another variable.

Declare a pointer variable

To declare a pointer variable, there must use  a *  (Asterisk) before variable name.

OUTPUT

Value at address

 Pointer pointing  to variable address
Fig: Pointer Pointing to a address

In the above example, there are two variable, first is normal variable ‘i’ & pointer variable ‘ptr’.

Integer variable “i” stores the value 10 at memory location 1024(for example) and pointer variable “ptr” stores the address of variable  ‘i’ at memory location 2322

Example

OUTPUT

Note: Pointer variable “ptr” prints the address of variable and “*ptr” prints the value of i. *variable name (*ptr) is also called value at address.

 Pointer in C Programming
Fig: Pointer in C Programming

OUTPUT

Note: When you run this program, address are printed might be different.

Managed by MochaHost - Fast & Easy WordPress Hosting