Wednesday, 29 July 2015
Preprocessor directive in C
The C Preprocessor is not part of the compiler, but is a separate step in the compilation
process. In simplistic terms, a C Preprocessor is just a text substitution tool
and they instruct compiler to do required pre-processing before actual
compilation. We'll refer to the C Preprocessor as the CPP.
All preprocessor commands begin with a
pound symbol (#). It must be the first nonblank character, and for readability,
a preprocessor directive should begin in first column. Following section lists
down all important preprocessor directives:
Directive
|
Description
|
#define
|
Substitutes a preprocessor macro
|
#include
|
Inserts a particular header from
another file
|
#undef
|
Undefines a preprocessor macro
|
#ifdef
|
Returns true if this macro is defined
|
#ifndef
|
Returns true if this macro is not
defined
|
#if
|
Tests if a compile time condition is
true
|
#else
|
The alternative for #if
|
#elif
|
#else an #if in one statement
|
#endif
|
Ends preprocessor conditional
|
#error
|
Prints error message on stderr
|
#pragma
|
Issues special commands to the
compiler, using a standardized method
|
Thursday, 16 July 2015
File Handling in C Language
A file represents a sequence of bytes on
the disk where a group of related data is stored. File is created for permanent
storage of data. It is a readymade structure.
In C
language, we use a structure pointer of file type to declare a file.
FILE *fp;
C
provides a number of functions that helps to perform basic file operations.
Following are the functions,
Function
|
description
|
fopen()
|
create a new file or open a
existing file
|
fclose()
|
closes a file
|
getc()
|
reads a character from a file
|
putc()
|
writes a character to a file
|
fscanf()
|
reads a set of data from a file
|
fprintf()
|
writes a set of data to a file
|
getw()
|
reads a integer from a file
|
putw()
|
writes a integer to a file
|
fseek()
|
set the position to desire
point
|
ftell()
|
gives current position in the
file
|
rewind()
|
set the position to the
begining point
|
Opening a
File or Creating a File
The fopen() function is used to create a new file or to open an
existing file.
General
Syntax :
*fp = FILE *fopen(const char *filename,
const char *mode);
Here filename is the name of the file to be
opened and mode specifies the purpose of opening the file. Mode can
be of following types,
*fp is the FILE pointer (FILE *fp), which will hold the reference to the opened(or created) file.
mode
|
description
|
r
|
opens a text file in reading
mode
|
w
|
opens or create a text file in
writing mode.
|
a
|
opens a text file in append
mode
|
r+
|
opens a text file in both
reading and writing mode
|
w+
|
opens a text file in both
reading and writing mode
|
a+
|
opens a text file in both
reading and writing mode
|
rb
|
opens a binary file in reading
mode
|
wb
|
opens or create a binary file
in writing mode
|
ab
|
opens a binary file in append
mode
|
rb+
|
opens a binary file in both
reading and writing mode
|
wb+
|
opens a binary file in both
reading and writing mode
|
ab+
|
opens a binary file in both
reading and writing mode
|
Closing a
File
The fclose() function is used to close an already opened file.
General
Syntax :
int fclose( FILE *fp );
Here fclose() function closes the file and returns zero on success, or EOF if there is an error in closing
the file. This EOF is a constant defined in the
header file stdio.h.
Input/Output
operation on File
In the
above table we have discussed about various file I/O functions to perform
reading and writing on file.getc() and putc() are simplest functions used to
read and write individual characters to a file.
#include<stdio.h>
#include<conio.h>
main()
{
FILE *fp;
char ch;
fp = fopen("one.txt",
"w");
printf("Enter data");
while(
(ch = getchar()) != EOF) {
putc(ch,fp);
}
fclose(fp);
fp = fopen("one.txt",
"r");
while(
(ch = getc()) != EOF)
printf("%c",ch);
fclose(fp);
}
Reading
and Writing from File using fprintf() and fscanf()
#include<stdio.h>
#include<conio.h>
struct emp
{
char
name[10];
int
age;
};
void main()
{
struct
emp e;
FILE
*p,*q;
p = fopen("one.txt",
"a");
q = fopen("one.txt",
"r");
printf("Enter Name and Age");
scanf("%s %d", e.name, &e.age);
fprintf(p,"%s
%d", e.name, e.age);
fclose(p);
do
{
fscanf(q,"%s
%d", e.name, e.age);
printf("%s %d", e.name, e.age);
}
while(
!feof(q) );
getch();
}
In this
program, we have create two FILE pointers and both are refering to the same
file but in different modes. fprintf() function directly writes into the file, while fscanf() reads from the file, which can
then be printed on console usinf standard printf() function.
Difference
between Append and Write Mode
Write (w)
mode and Append (a) mode, while opening a file are almost the same. Both are
used to write in a file. In both the modes, new file is created if it doesn't
exists already.
The only
difference they have is, when you open a file in the write mode, the file is
reset, resulting in deletion of any data already present in the file. While in
append mode this will not happen. Append mode is used to append or add data to
the existing data of file(if any). Hence, when you open a file in Append(a)
mode, the cursor is positioned at the end of the present data in the file.
Reading
and Writing in a Binary File
A Binary
file is similar to the text file, but it contains only large numerical data.
The Opening modes are mentioned in the table for opening modes above.
fread() and fwrite() functions are used to read and write is a binary
file.
fwrite(data-element-to-be-written,
size_of_elements,
number_of_elements,
pointer-to-file);
fread() is also used in the same way, with the same
arguments like fwrite() function. Below mentioned is a simple example of
writing into a binary file
const char *mytext = "The quick
brown fox jumps over the lazy dog";
FILE *bfp= fopen("test.txt",
"wb");
if (bfp) {
fwrite(mytext,
sizeof(char), strlen(mytext), bfp) ;
fclose(bfp) ;
}
fseek(),
ftell() and rewind() functions
·
fseek() - It is used to move the reading
control to different positions using fseek function.
·
ftell() - It tells the byte location of
current position of cursor in file pointer.
·
rewind() - It moves the control to
beginning of the file.
Tuesday, 30 June 2015
C Programming Dynamic Memory Allocation
The exact size of array is unknown until the compile time,i.e., time when a compiler compiles code written in a programming language into a executable form. The size of array you have declared initially can be sometimes insufficient and sometimes more than required. Dynamic memory allocation allows a program to obtain more memory space, while running or to release space when no space is required.
Although, C language inherently does not has any technique to allocated memory dynamically, there are 4 library functions under
"stdlib.h"
for dynamic memory allocation.Function | Use of Function |
---|---|
malloc() | Allocates requested size of bytes and returns a pointer first byte of allocated space |
calloc() | Allocates space for an array elements, initializes to zero and then returns a pointer to memory |
free() | dellocate the previously allocated space |
realloc() | Change the size of previously allocated space |
malloc()
The name malloc stands for "memory allocation". The function
malloc()
reserves a block of memory of specified size and return a pointer of type void
which can be casted into pointer of any form.Syntax of malloc()
ptr=(cast-type*)malloc(byte-size)
Here, ptr is pointer of cast-type. The
malloc()
function returns a pointer to an area of memory with size of byte size. If the space is insufficient, allocation fails and returns NULL pointer.ptr=(int*)malloc(100*sizeof(int));
This statement will allocate either 200 or 400 according to size of
int
2 or 4 bytes respectively and the pointer points to the address of first byte of memory.calloc()
The name calloc stands for "contiguous allocation". The only difference between malloc() and calloc() is that, malloc() allocates single block of memory whereas calloc() allocates multiple blocks of memory each of same size and sets all bytes to zero.
Syntax of calloc()
ptr=(cast-type*)calloc(n,element-size);
This statement will allocate contiguous space in memory for an array of n elements. For example:
ptr=(float*)calloc(25,sizeof(float));
This statement allocates contiguous space in memory for an array of 25 elements each of size of float, i.e, 4 bytes.
free()
Dynamically allocated memory with either calloc() or malloc() does not get return on its own. The programmer must use free() explicitly to release space.
syntax of free()
free(ptr);
This statement cause the space in memory pointer by ptr to be deallocated.
Examples of calloc() and malloc()
Write a C program to find sum of n elements entered by user. To perform this program, allocate memory dynamically using malloc() function.
#include <stdio.h>
#include <stdlib.h>
int main(){
int n,i,*ptr,sum=0;
printf("Enter number of elements: ");
scanf("%d",&n);
ptr=(int*)malloc(n*sizeof(int)); //memory allocated using malloc
if(ptr==NULL)
{
printf("Error! memory not allocated.");
exit(0);
}
printf("Enter elements of array: ");
for(i=0;i<n;++i)
{
scanf("%d",ptr+i);
sum+=*(ptr+i);
}
printf("Sum=%d",sum);
free(ptr);
return 0;
}
Write a C program to find sum of n elements entered by user. To perform this program, allocate memory dynamically using calloc() function.
#include <stdio.h>
#include <stdlib.h>
int main(){
int n,i,*ptr,sum=0;
printf("Enter number of elements: ");
scanf("%d",&n);
ptr=(int*)calloc(n,sizeof(int));
if(ptr==NULL)
{
printf("Error! memory not allocated.");
exit(0);
}
printf("Enter elements of array: ");
for(i=0;i<n;++i)
{
scanf("%d",ptr+i);
sum+=*(ptr+i);
}
printf("Sum=%d",sum);
free(ptr);
return 0;
}
realloc()
If the previously allocated memory is insufficient or more than sufficient. Then, you can change memory size previously allocated using realloc().
Syntax of realloc()
ptr=realloc(ptr,newsize);
Here, ptr is reallocated with size of new size.
#include <stdio.h>
#include <stdlib.h>
int main(){
int *ptr,i,n1,n2;
printf("Enter size of array: ");
scanf("%d",&n1);
ptr=(int*)malloc(n1*sizeof(int));
printf("Address of previously allocated memory: ");
for(i=0;i<n1;++i)
printf("%u\t",ptr+i);
printf("\nEnter new size of array: ");
scanf("%d",&n2);
ptr=realloc(ptr,n2);
for(i=0;i<n2;++i)
printf("%u\t",ptr+i);
return 0;
}
Subscribe to:
Posts (Atom)