SlideShare a Scribd company logo
1 of 118
Understanding C File Handling
Functions With Examples
Contributed by faribasiddiq () On 12th January, 2014
This is an article on Understanding C File Handling Functions
With Examples in C.
Data files are very essential part of in computer programming.
The data we use while programming using the variables of
different data types, are unavailable after the program
execution. So,there is no way to retrieve the data if we further
need. Here comes the necessity of data files.
 FILE Structure
 fopen
 fclose
 File Access Mode
 fputs
 fgets
 fputc
 fgetc
 fprintf
 fscanf
 fwrite
 fread
 freopen
 fflush
 feof
 fseek
 ftell
 fgetpos
 fsetpos
 rewind
 perror
 Binary files
FILE Structure
FILE is a structure that is used for data storage. The structure
of FILE is:
Code:
typedef struct
{
int level;
unsigned flags;
char fd;
unsigned char hold;
int bsize;
unsigned char_FAR* buffer;
unsigned char_FAR* curp;
unsigned istemp;
short token;
}FILE;
But for using FILE in our program, we need not go through the
members of the FILE structure. We can just use FILE pointer to
create and use FILE for different operations.
Prototype
FILE* filePointerName;
Example:
Code:
FILE *fp;
FILE *inFile;
FILE *outFIle
fopen()
Prototype
fopen(“fileName”,”mode”);
Example:
Code:
FILE *fp = fopen("test.txt","w");
FILE *inFile = fopen("test.txt","r");
fclose()
Prototype
fclose(filePointer);
Example:
Code:
FILE *fp = fopen("test.txt","w");
fclose(fp);
File Access Mode
While opening a file, we have to specify the mode for opening
the file. Here is a list of different modes for opening any file and
usage of these mode.
r - Read mode - Read from a specified file which already
exists. If the file doesn’t exist or is not found, this operaiton
fails.
r+ - Read mode(+ some others) - Read from and write into an
existing file. The file must exist before the operation.
w - Write mode - Create new file with specified name. If the file
exists, contents of the file is destroyed.
w+ - Write mode(+ some others) - Write into an file. It also
permits to read the data.
a - Append mode - It appends content to the specified file. If
the file doesn’t exist, it is created first, and then contents are
written into it.
a+ - Append mode(+some others) - Open a file for reading
and appending.
Example:
Here is an example of opening a file in write mode. First, a file
pointer fp is declared. Then fp is used to open a file named
“test.txt” in ‘w’ mode, which stands for write mode.If fp is null, it
means that file could not be opened due to any error.
Code:
int main()
{
FILE *fp;
fp = fopen("test.txt","w");
if(fp==NULL)
{
printf("Error in openinng file");
}
else
printf("File has been created successfully");
}
In file handling, we will use some data types besides the
common data types. Here goes some discussion on these data
types:
size_t - It represents the size of any object in byte. For example,
the sizeof() function returns the size of any object in size_t type
which is unsigned integral type.
fpos_t - It is used to specify a position within a file.
In different portions of the program, we may need to get and set
the position of file pointer, Generally, any fpos_t object is filled
by callingfgetpos() function and the position is read
by fsetpos() function.
Now we will understand in brief the major functions needed for
file handling in C.
fputs()
fputs is used to write data in file. Prototype of this function is:
int fputs(const char* str, FILE* stream );
Parameters
str: constant character pointer or string that is to be written in
the file.
stream: pointer to the file in which the data is to be written.
Return
Type: integer
Value: On success Non negative value and
On failure: End of file(EOF), setting the error indicator
fgets()
fgets is used to read data from file. Prototype of this function is:
char* fgets(char* str,int count,FILE* stream);
Parameters
str: character pointer that will point to the returned data from
file.
count: integer that is the maximum count of character to return
from the file.If the number is n, then (n-1) character is returned
from the file. If the number of characters is less than n-1, then
full data from the file will be returned.
stream: pointer to the file from which the data will be fetch.
Return:
Type: character pointer(char*)
Value: On success String which is read
On failure Null pointer, setting the error indicator
Example fputs and fgets
Code:
int main()
{
FILE* fp;
char ch[20];
fp = fopen("testFile.txt","w");
if(fp == NULL)
printf("Error in creating file");
else
fputs("This is a test file",fp);
fclose(fp);
fp = fopen("testFile.txt","r");
if(fp == NULL)
{
printf("Error in opening file");
}
else
{
fgets(ch,20,fp);
printf("n%s",ch);
}
getch();
return 0;
}
In this example, a file is opened in write mode. After successful
opening, a string is put in the file using fputs() function. The file
is then closed and again opened in read mode. Next using
fgets() function, twenty characters are read from starting
position of the file and printed it on the console.
fputc()
It is used to write one by one character in file. Function
prototype is:
int fputc ( int character, FILE * stream );
Parameters
character: The character to be written in the file.
stream: pointer to the file in which data will be written.
Return
Type: integer
Value: On success Integer value of the character which is
written
On Failure EOF is returned, setting the error indicator.
A character is written in the position specified by the file pointer.
After the write operation of every character, file pointer
increases by one and moves to the next position.
Example
Code:
int main()
{
FILE * fp;
int len, count;
char buffer[20] = "Good morning";
len = strlen(buffer);
fp = fopen ("file.txt","w");
if (fp == NULL) printf ("Error in opening file");
else {
for(count = 0; count < len; count++)
fputc(buffer[count],fp);
fclose (fp);
}
return 0;
}
In this function, a string is defined at the beginning. After
opening a file in write mode, if successfully opened, copy the
string by one character after another. Here, fputc() is used to
write the character in the file.
fgetc()
It is used to read one by one character from file. Function
prototype is:
int fgetc ( FILE * stream );
Parameters
stream: Pointer to the file from which data will be read.
Return
Type: integer
Value: On Success integer value of the character which is read
On Failure Null pointer, setting the error indicator
It returns the character which is currently pointed by the FILE
pointer.
Example
Code:
int main()
{
FILE * fp;
int count = 0;
char ch;
fp = fopen ("file.txt","r");
if (fp == NULL) printf ("Error in opening file");
else {
while((ch = fgetc(fp)) != EOF)
count++;
printf("There are %d words in the file",count);
fclose (fp);
}
return 0;
}
Here, a file is opened in read mode. Then until the end of file,
characters are read from the file(with punctuation and
space)using fgetc()and count of characters are increased.
When it reaches EOF, total number of character is printed on
the screen.
fprintf()
fprintf() works like printf(), with some differences. While printf()
works for standard ouput, fprintf() is for file writing. The protype
is:
int fprintf(FILE * stream, const char* str);
Parameters
stream: pointer to the file in which the data is to be written.
str: character pointer to the data to be wriitten, which can
include the format of the data.
Return
Type: integer
Value: On success number of characters which is written
On Failure Negative number.
Example
Code:
int main()
{
char* book[] = {"Shonchoyita","Shonchita","Oporajito","Bonolota"};
char* author[] =
{"Rabindranath","Nazrul","Bivutibhushan","Jibonanondo"};
FILE* fp;
int count;
fp = fopen("BookList.txt","w");
if(fp == NULL)
{
printf("Error in opening file");
}
else
{
for(count = 0; count < 4; count++)
{
fprintf(fp,"%-10s %-10sn",book[count],author[count]);
}
}
fclose(fp);
}
In this example, arrays of book and author are defined. A text
file named BookList.txt is opened in write mode. Then the data
of book and author is written into this file using a file pointer and
fprintf() function.
fscanf()
fscanf() works like scanf() function, with some differences.
While scanf() works for standard input, fscanf() is for file
reading. The prototype is:
int fscanf(FILE * stream, const char* str);
Parameters
stream: pointer to the file from which the data is to be read.
str: character pointer to the data to be read. It is mainly the
format of the data.
Return
Type: integer
Value: On success number of arguments which is filled
On failure error indicator is set and EOF is returned.
Example
Now, we will perform the file read operation using fscanf()
function from the BookList.txt file we have created previously.
Code:
int main()
{
FILE* fp;
char bookName[50],bookAuthor[50];
fp = fopen("BookList.txt","r");
if(fp == NULL)
{
printf("Error in opening file");
}
else
{
while(fscanf(fp,"%s %s",bookName,bookAuthor)!= EOF)
{
printf("%-10s t%-10sn",bookName,bookAuthor);
}
}
}
In this example, existing text file BookList.txt is opened in read
mode. Then, using the file pointer, the book name and author
name is read from the file using fscanf() funciton and pointed by
two characters stored in two character array named bookName
and bookArray until the end of file is found. After every read
operation, the result is shown in the console using printf()
function.
fwrite()
It is used for file writing. Prototype is:
size_t fread(const void* ptr,size_t size,size_t count,FILE* stream)
Parameters:
ptr: pointer to the data which will be stored.
size: the size of data elements (in byte) to be written.
count: number of data elements to be written.
stream: the pointer to the file where the data will be written.
Return
Type: size_t
Value: On success number of elements which are successfully
written
On failure zero (0) if the size or count is 0. Error indicator is set.
Example
Code:
int main()
{
struct book
{
char title[20];
char author[20];
};
struct book bengaliBook[4] = {
"Shonchita","Rabindranath",
"Shonchoyita","Nazrul",
"Oporajito","Bivutibhushan",
"Bonolota","Jibonananda"
};
FILE* fp;
int count;
fp = fopen("BookList.txt","w");
if(fp == NULL)
{
printf("Error in opening file");
}
else
{
for(count = 0; count < 4; count++)
{
fwrite(&bengaliBook[count],sizeof(bengaliBook[count]),1,fp);
}
}
fclose(fp);
return 0;
}
In this example, a book structure with two member-title and
author is declared. A structure array bengaliBook is declared
and initialized. Then a file named BookList.txt is opened in write
mode. Then, the four elements of the structure array is written
in the file, each of which(elements) contains a book title and
author name.
fread()
It is used to read data from file. Prototype of the function is:
size_t fread (void* ptr,size_t size,size_t count,FILE* stream)
Parameters
ptr: pointer to memory where the read data will be stored.
size: size of data elements (in byte) to be read.
count: number of data elements to be read.
stream: pointer to the file from which the data will be read.
Return
Type: size_t
Value: On success number of elements which are successfully
read.
On failure returns zero (0) if the size or count is 0, Error
indicator is set.
Example
Code:
int main()
{
struct book
{
char title[20];
char author[20];
}banglaBook;
FILE* fp;
int count;
fp = fopen("BookList.txt","r");
if(fp == NULL)
{
printf("Error in opening file");
}
else
{
for(count = 0; count < 4; count++)
{
fread(&banglaBook, sizeof(banglaBook),1,fp);
printf("%-10s %-10sn",banglaBook.title,banglaBook.author);
}
}
fclose(fp);
return 0;
}
In this example, the same book structure is used. A structure
variable named banglaBook is declared. Then the text file
BookList.txt is opened in read mode. We have written four
elements of the book structure array named bengalibook in this
text file in previous example. Now we will read those
information. Using file pointer, every time we read data from the
text file. The size of the read data in every iteration of the loop
is equal to the size of the book structure variable banglaBook.
Then the read data is displayed in the console.
freopen()
It is used to reopen a file. Prototype is:
FILE *freopen(const char *filename, const char *mode, FILE *stream)
Parameters
filename: Name of the file which is to be re opened.
mode: Access mode of the file .
stream: Pointer to a FILE object that identifies the stream to be
reopened.
Return
TYPE: File pointer.
Value: On success pointer to the file which is reopened.
On failure NULL pointer.
The third parameter is the file stream associated with the
specified file. The file is accessed with the specified access
mode and associates with it the file stream. If this stream is
already associated with some other file(s), then this function
first closes the files, disassociates the stream, opens the
specified file and associates it with the stream.
Example
Code:
int main ()
{
FILE *fp;
fp = freopen("file.txt", "w", stdout);
if(fp == NULL)
printf("Error in reopening file");
else
printf("hi world from consolen");
fclose(fp);
return(0);
}
In this example, freopen() associates stdout with file.txt with
write access mode. So, anything available on the stdout
stream, is written into file.txt. After running the example, we will
see that “hi world from console”, which is available in standard
output, has been written in file.txt.
fflush()
It is used to flush buffer. Prototype is:
int fflush ( FILE * stream );
Parameters
stream: Pointer to a file that specifies a buffered stream.
Return
Type: integer
Value: 0 On success.
On failure a number indicating the error type
Use case of fflush() is platform dependent. Generally it is used
to clear the output buffer before any input operation.
Example
Code:
char buffer[50];
int main() {
FILE * fp;
fp = fopen ("file.txt","r+");
if (fp == NULL) printf ("Error in opening file"); else {
fputs ("Brazil",fp);
fflush (fp);
fgets (buffer,20,fp);
fclose (fp);
return 0;
}
}
In this example, after between fputs() and fgets() operation,
fflush() is used to clear the buffer.
feof()
It is used to check whether end of file for a stream is set or not.
Prototype of the function is:
int feof ( FILE * stream );
Parameters
stream - Pointer to a file.
Return
Type: integer
Value: Non zero value if EOF is set for the stream Zero
Otherwise.
By using file pointer as a parameter of feof(), we can check
whether end of file has been reached or not.
Example
Code:
int main () {
FILE * fp;
int n = 0;
fp = fopen ("file.txt","r");
if (fp==NULL) printf ("Error opening file"); else {
while (fgetc(fp) != EOF) {
continue;
}
if (feof(fp)) {
puts ("End of file");
} else puts ("Something wrong, error of file not found");
fclose (fp);
}
return 0;
}
In this example, we have read the content of the file by each
character till the end of file and have checked whether the end
of file is found or not.
fseek()
It is used to set file pointer to any position. Prototype is:
int fseek ( FILE * stream, long int offset, int origin );
Parameters
Stream: pointer to a file.
Offset: Number of bytes or characters from the origin.
Origin: The original position is set here. From this position,
using the offset, the file pointer is set to a new position.
Generally, three positions are used as origin:
SEEK_SET - Beginning of file
SEEK_CUR - Current position of the file pointer
SEEK_END - End of file
Return
Type: Integer
Value: On success Zero (0)
On failure Non-Zero
Example
Code:
int main () {
FILE * fp;
fp = fopen ( "file.txt" , "w" );
if (fp==NULL)
printf ("Error in opening file"); else {
fputs ( "I am supporter of France." , fp );
fseek ( fp , 18 , SEEK_SET );
fputs ( "Brazil" , fp );
fseek( fp , 0 , SEEK_CUR );
fputs ( " and Portugal" , fp );
fclose ( fp );
}
return 0;
}
Then using SEEK_SET and offset, the word France is replaced
by Brazil. Then by using SEEK_CUR, and position is appended
with the string.
ftell()
It is used to get current position of the file pointer. The function
prototype is:
long int ftell ( FILE * stream );
Parameters
stream: Pointer to a file.
Return
Type: long integer.
Value: On success value of current position or offset bytes
On failure -1. System specific error no is set
Example
Code:
int main () {
FILE * fp;
long int len;
fp = fopen ("file.txt","r");
if (fp==NULL)
printf ("Error in opening file"); else {
fseek (fp, 0, SEEK_END);
len=ftell (fp);
fclose (fp);
printf ("The file contains %ld characters.n",len);
}
return 0;
}
In this example, file.txt is opened and using fseek(), file pointer
is set to the end of the file. Then, ftell() is used to get the
current position, i.e. offset from the beginning of the file.
fgetpos()
It is used to get current position of the file stream. Prototype of
the function is:
int fgetpos ( FILE * stream, fpos_t * pos );
This function gets the current position of the file pointer and
stores it in fpos_t object. Then we can set the file pointer to this
position in any time and perform required operation.
Prameters
stream: Pointer to a file stream.
pos: Pointer to an object that stores the position value.
Return
Type: integer
Value: On success zero(0)
On failure system specific error no.
fsetpos()
It is used to set current position of the file pointer. Function
prototype:
int fsetpos ( FILE * stream, const fpos_t * pos );
In the fpos_t pointer pos, a position is specified. The file pointer
is then set to this position.
Parameters
stream: Pointer to a file.
pos: Pointer to a fpos_t object. The position to which the file
pointer is to be set is previously stored here.
Return
Type: integer
Value: On success zero(0).
On failure system specific error no.
Example fgetpos fsetpos
Code:
int main () {
FILE * fp;
fpos_t pos;
fp = fopen ("file.txt","w");
if (fp==NULL)
printf ("Error in opening file"); else {
fgetpos (fp, &pos);
fputs ("France is my favourite team",fp);
fsetpos (fp, &pos);
fputs ("Brazil",fp);
fclose (fp);
}
return 0;
}
The above example clarifies both fgetpos() and fsetpos()
function. After opening file, fgetpos() is used to get the initial
position of the file pointed by file pointer fp and store it into
fpos_t pointer pos. Then some text is written into the file, so file
pointer is now changed. If we want to set the file pointer to the
starting of the file, we can use fsetpos() function. This function
sets the current position of the file pointer to the position
pointed by fpos_t pointer pos, which is now the initial position of
the file.
rewind()
It is used to set the file pointer at the beginning of the file.
Function prototype:
void rewind ( FILE * stream );
Parameters
stream: Pointer to a file.
In any stage of the program, if we need to go back to the
starting point of the file, we can use rewind() and send the file
pointer as the parameter.
Example
Code:
int main () {
int n;
FILE * fp;
fp = fopen ("file.txt","w+");
if (fp==NULL)
printf ("Error in opening file"); else {
fputs ("France is my favorite team",fp);
rewind (fp);
fputs("Brazil",fp);
fclose (fp);
}
return 0;
}
In the above example, first, some string is written in the file.
Then rewind() is used to set the file pointer at the beginning of
the file. Then overwrite a word.
perror()
It is used to print error message. Function prototype:
void perror ( const char * str );
Parameters
str: String that contains the custom error message is provided
by the developer. It may be null pointer, if no custom message
is intended to provide. Conventionally, application name is used
as the parameter.
Handling error message?
Whenever an error occurs, an error no is generated (header file
– errno.h). This error no is associated with specific error
message.
So, whenever we get an error, we can print the error using
perror() to see exactly what happened. But remember, the
system error message is platform dependent.
If we want to give a custom error message along with the
system error message, we have to sent the error message as a
parameter to perror() function like- perror(“custom error
message.”). The error message will be printed in
stderr(standard error output stream).
The format of printed error message is:
Code:
Custom error message: System error message.
If no custom error message is sent, then only the system error
message is printed:
System error message.
Whenever there is a possibility of occurring any error, we
should use perrror() function.
Example
Code:
int main () {
FILE * pFile;
pFile=fopen ("unexist.ent","rb");
if (pFile==NULL)
perror ("The following error occurred"); else
fclose (pFile);
return 0;
}
Output:
Code:
ERROR: No such file or directory
Example 2: with no parameter in perror().
Code:
int main () {
FILE * fp;
fp = fopen ("fileTest.txt","r");
if (fp==NULL)
perror (""); else
fclose (fp);
return 0;
}
Output:
Code:
No such file or directory
Binary files
We can handle any binary file and perform the above
fucntionalities in those files. The main difference between
binary file and text file handling is access mode. We have to
add a character ‘b’ with each of access mode while working
with binary file. For example, ‘rb’ is used for read mode while
‘wb’ is used for write mode for binary file accessing.
From the above discussion, we have learnt some useful
lessons for file handling in C. Hopefully it will help us to perform
basic file I/O operations.
Understanding File Descriptor
and File Pointer
Contributed by Trinity On 25th August, 2012
This is an article on Understanding File Descriptor and File
Pointer in C.
During C programming, file operations are pretty common. And
when you are writing programs in C on Linux, two familiar terms
related to file operations are File Pointers and File Descriptors.
We know both are different, but what are they? This article will
focus on understanding what are file descriptors, file pointers
and how are they related at the kernel level.
Understanding individually
File Descriptor is an integer value at the kernel level which
identifies the file to be operated during the program. Here, its
worth mentioning, that everything on Linux is a file.
In C system programming, we have following method to open a
file:
Code:
int fd = open ("/etc/myfile.txt", O_WRONLY);
This system call returns the file descriptor.
However, Standard C also provides another method for
opening a file,
Code:
FILE *fp = fopen ("/etc/myfile.txt", "w");
This C library method returns a file pointer.
File Pointer is a pointer to a C structure, identifying a file,
wrapping the file descriptor, buffering functionality and all other
functionality needed for I/O operation.
The file pointer is of type FILE, whose definition can be found in
"/usr/include/stdio.h". This definition may vary from one
compiler to another.
Here is one such definition:
Code:
typedef struct {
unsigned char *_ptr;
int _cnt;
unsigned char *_base;
unsigned char *_bufendp;
short _flag;
short _file;
int __stdioid;
char *__newbase;
#ifdef _THREAD_SAFE
void *_lock;
#else
long _unused[1];
#endif
#ifdef __64BIT__
long _unused1[4];
#endif /* __64BIT__ */
} FILE;
Hence, talking about differences between a file pointer and a
file descriptor,
 File Pointer includes various I/O functionality like buffering,
EOF detection, etc whereas File Descriptor does not.
 File Pointer is the most widely used and standardized,
however, File Descriptor is a low level kernel variable and
limited to Linux.
Deeper Understanding - At the Kernel
level
The Kernel maintains a Kernel File Table for every open file by
any process. Each entry in this kernel file table is identified by
our File Descriptor. Hence, any file opened by any process
would have a file descriptor and that file would have its entry
maintained in the kernel file table until it is closed. Another
interesting fact is, even if the same file on the disk is opened by
two different processes, they would have their own separate file
table entries in the kernel file table with separate file descriptor
values. This is needed to store the mode of open, current file
position, etc for each opened instance of the file.
Generally, an entry in the kernel file table would consist of:
 File Descriptor
 Current File Position
 inode info
 vnode info
 file metadata
 etc
However, every process also has its own File Descriptor (FD)
table, which is basically a data structure identifying the opened
file instance and includes a pointer to the entry in the kernel file
table. Each entry in this FD table is of the opened file in the
process.
At the userspace level, the file pointer is used to read/write onto
a file. Whereas, at the system level, it uses the lower level
variable file descriptor.
Here is an abstract illustration:
So, when we write the code
Code:
1. File *fp;
2. fp = fopen ("/etc/myfile.txt", "w");
3. fclose(fp);
In statement 1, a 4 byte memory for the pointer is created of
type 'FILE' on stack.
In statement 2, a memory = 'sizeof(FILE)' is allocated on heap,
and address of which is assigned to the pointer 'fp'.
Along with, a new entry created in the FD table of the process
followed by, an entry created in the kernel file table
representing the newly opened file instance having a unique
FD.
During the read/write/other IO operations, values are
maintained by the Kernel File Table entry.
In statement 3, all the allocated memory for file pointer is
released and the entry is deleted.
File Pointer from File Descriptor
Use method
Code:
FILE * fdopen (int fd, const char *mode);
The header file is "stdio.h"
Example:
Code:
#include <stdio.h>
#include <fcntl.h>
int main()
{
int fd;
FILE *fp;
fd = open ("myfile.txt", O_WRONLY | O_APPEND| O_CREAT);
if (fd < 0)
{
printf("Error opening file through FDn");
exit (1);
}
write (fd, "Writing using FDn", 17);
fp = fdopen(fd, "a");
fprintf(fp, "Writing using File Ptrn");
fclose (fp);
close(fd);
return 0;
}
Here is the Output:
Code:
[fedora@fedora16 fdfptr]$ sudo cat myfile.txt
Writing using FD
Writing using File Ptr
File Descriptor from File Pointer
Code:
int fileno(FILE * fp);
The header file is again "stdio.h".
Example:
Code:
#include <stdio.h>
#include <fcntl.h>
int main()
{
int fd;
FILE *fp;
fp = fopen ("myfile.txt", "a+");
if (fp == NULL)
{
printf("Error opening file through FPn");
exit (1);
}
fprintf(fp, "Writing using File Ptrn");
fd = fileno (fp);
write (fd, "Writing using FDn", 17);
fclose (fp);
close(fd);
return 0;
}
Here is the Output:
Code:
[fedora@fedora16 fdfptr]$ sudo cat myfile.txt
Writing using FD
Writing using File Ptr
Conclusion
Now we know what internally file descriptor and file pointer is,
and how they work in their respective spaces. Also, we know
how to get one from the other. So, keep playing and exploring
and share any interesting fact you get across.
Opening A File
Before we can write information to a file on a disk or read it, we
must open the file. Opening a file establishes a link between
the program and the operating system, about, which file we are
going to access and how. We provide the operating system
with the name of the file and whether we plan to read or write to
it. The link between our program and the operating system is a
structure called FILE which has been defined in the header file
“stdio.h” . Therefore, it is necessary to always include this file
when we are doing high level disk I/O. When we request the
operating system to a file, what we get back is a pointer to the
structure FILE. That is why, we make the following declaration
before opening the file,
FILE*fp ;
Each file we open will have its own FILE structure. The FILE
structure contains information about the file being used, such
as its current size, its location in memory etc. More importantly
it contains a character pointer which points to the character that
is about to get read.
Now let us understand the following statements,
FILE *fp ;
fp = fopen ( “PR1.C”, “r” ) ;
fp is a pointer variable, which contains address of the structure
FILE which has been in the header file “stdio.h”.
fopen( ) will open a file “PR1.C” in ‘read’ mode, which tells the
compiler that we would be reading the contents of the file. Note
that “r” is a string and not a character; hence the double quotes
and not single quotes.
In fact, fopen( ) performs three important tasks when you open
the file in “r” mode:
(a) Firstly it searches on the disk the file to be opened.
(b) If the file is present, it loads the file from the disk into
memory. Of course if the file is very big, then it loads the file
part by part.If the file is absent, fopen( ) returns a NULL.NULL
is a macro defined in “stdio.h” which indicates that you failed to
open the file.
(c) It sets up a character pointer which points to the first
character of the chunk of memory where the file has been
loaded.
Reading from A file
Once the file has been opened for reading using fopen( ), the
file’s contents are brought into memory and a pointer points to
the very first character. To read the file’s contents from memory
there exists a function called fgetc( ). This has been used in our
sample program through,
ch = fgetc ( fp ) ;
fgetc( ) reads the character from current pointer position,
advances the pointer position so that it now points to the next
character, and returns the character that is read, which we
collected in the variable ch. Note that once the file has been
opened, we refer to the file through the file pointer fp.
We have to use the function fgetc( ) within an indefinite while
loop. There has to be a way to break out of this while,it is the
moment we reach the end of file. End of file is signified by a
special character in the file, when it is created. This character
can also be generated from the keyboard by typing ctrl Z.
While reading from the file, when fgetc( ) encounters this
special character, instead of returning the character that it has
read, it returns the macro EOF. The EOF macro has been
defined I the file “stdio.h”. In place of the function fgetc( ) we
could have as well used the macro getc( ) with the same effect.
Opening A File
There is a possibility that when we try to open a file using the
function fopen( ), the file may not be opened. While opening the
file in “r” mode, this may happen because the file being opened
may not be present on the disk at all. And you obviously cannot
read a file which doesn’t exist. Similarly, while opening the file
for writing, fopen( ) may fail due to a number of reasons, like,
disk space may be insufficient to open a new file, or the disk
may be write protected and so on.
So it is important for any program that accesses disk files to
check whether a file has been opened successfully before
trying to read or write to the file. If the file opening fails due to
any of the several reasons mentioned above, the fopen( )
function returns a value NULL (defined in “stdio.h” as #define
NULL 0).
Here is how this can be handled in a program…
Code: C
#include “stdio.h”
main()
{
FILE*fp ;
Fp = fopen ( “PR1.C”,”r” ) ;
if( fp == NULL )
{
puts ( “cannot open file” ) ;
exit() ;
}
}
File Opening Modes
We open the file in read ( “r” ) mode. However, “r” is but one of
the several modes in which we can open a file. Following is a
list of all possible modes in which a file can be opened . the
tasks performed by fopen( ) when a file is opened in each of
these modes are also mentioned.
r :- Searches file. If the file exists, loads it into memory and sets
up a pointer which points to the first character in it. If the file
doesn’t exit it returns NULL.
Operations possible – reading from the file.
w :- Searches file. If the file exists, its contents are overwritten.
If the file doesn’t exit, a new file is created. Returns NULL, if
unable to open file.
Operations possible – writing to the file.
a :- Searches file. If the file exists, loads it into memory and
sets up a pointer which points to the first character in it. If the
file doesn’t exist, a new file is created. Returns NULL, if unable
to open file.
Operations possible – appending new contents at the end of
file.
r+ :- Searches file. If it exists, loads it into memory and sets up
a pointer which points to the first character in it. If file doesn’t
exist it returns NULL.
Operations possible – reading existing contents, writing new
contents, modifying existing contents of the file.
w+ :- Searches file. If the file exists, its contents are destroyed.
If the file doesn’t exist a new file is created. Returns NULL, if
unable to open file.
Operations possible – writing new contents, reading them back
and modifying existing contents of the file.
a+ :-Searches file. If the file exists, loads it in to memory and
sets up a pointer which points to the first character in it. If the
file doesn’t exist, a new file is created. Returns NULL, if unable
to open file.
Operations possible – reading existing contents, appending
new contents to end of file. Cannot modify existing contents.
Writing to A File
The fputc( ) function is similar to the putch( ) function, in the
sense that both output characters. However, putch( ) function
always writes to the VDU, whereas, fputc( ) writes to the file.
Which file? The file signified by ft. the writing process continues
till all characters from the source file have been written to the
target file, following which the while loop terminates.
We have already seenthe function fgetc( ) which reads
characters from a file. Its
Counterpart is a function called fputc( ) which writes characters
to a file. As a practical use of these character I/O functions we
can copy the contents of one file into another, as demonstrated
in the following example. This program takes the contents of a
text file and copies them into another text file, character by
character.
Example
Code: C
#include “stdio.h”
main()
{
FILE *fs, *ft ;
char ch ;
fs = fopen ( “pr1.c”, “r” ) ;
if ( fs == NULL )
{
puts ( “Cannot open source file” ) ;
exit( ) ;
}
ft = fopen ( “pr2.c”, “w” ) ;
if ( ft == NULL )
{
puts ( “Cannot open target file” ) ;
fclose ( fs ) ;
exit( ) ;
}
while ( 1 )
{
ch = fgetc ( fs ) ;
if ( ch == EOF )
break ;
else
fputc ( ch, ft ) ;
}
fclose ( fs ) ;
fclose (t
}
Closing The File
When we have finished reading from the file, we need to
close it. This is done using the function fclose( ) through
the statement,
fclose ( fp ) ;
this deactivates the file and hence it can no longer be
accessed using getc( ). Once again we don’t use the
filename but the file pointer fp. Loops in C -
for while do while and goto
Contributed by faribasiddiq () On 22nd December, 2013
This is an article on Loops in C - for while do while and
goto in C.
Loops are the basic logic building structures in computer
programming. It is a way of executing statement(s) repeatedly
in specified times, which is termed as iteration.
Here different types of loops in C language will be discussed.
All of them have same goal, but their way of working is
different. The topics of discussion of this article would be to
understand the following loops in C programming:
 for Loop
 while Loop
 do while Loop
 goto
for Loop
It is very easiest to understand out of all loops. Generally it is
used when number of iteration is known to a programmer.
Traditionally, a basic for loop has four parts:
 Initialization
 Condition
 Update(Increment/Decrement)
 Statements
Here is the basic syntax of for loop.
Code:
for (variable(s) initialization; condition(s); update value of variable(s))
{
statement 1;
. . . .
. . . .
. . . .
statement N;
}
For a beginner, it must not be that easy to understand the
syntax. For elucidation, an example is given:
Code:
int main()
{
int i;
for(i = 0; i < 5; i++)
printf("%d", i);
}
Illustration for different parts of the loops for above example is
as follows:
 i = 0 initialize the loop control variable i.
 i < 5 is condition for the loop. The loop continues till the value of
i is less than 5.
 i++ increments the value of i by 1. It means i+1.
 printf("%d", i) is the statement of the loop. Value of i is
displayed in the console by this statement.
The steps involved in working of the above example are:
Step 1: i = 0. So condition (i < 5) is true. Update the value of i
by 1. But the updated value will work for next iteration. Print the
value of i. The value that will be printed will be 0.
Step 2: Now i = 1. So Condition is true. Update the value of i by
1. But the updated value will work for next iteration. Print the
value of i. The value that will be printed will be 1.
Step 3, 4, 5: Working procedure is as the previous one and
print the value 2,3,4 accordingly.
Step 6: Now i = 5. So Condition is false. So, exit the loop.
So the building blocks of for loop are:
 Initialize the loop variable(s).
 Check the condition for next iteration.
 Update the value of loop variable.
 Statement(s).
The value of loop control variable can be updated by any
amount. For example, i+=2 can be used for incrementing the
value by 2. Some other operators can be used for updating the
value of loop control variable such as decrement (-),
multiplication (*), divide (-) etc. besides increment operator (+).
The benefit of using for loop is immense. An example may help
in explanation. Suppose you will be given two numbers x and y.
You have to find out the summation of all numbers from x to y
including these numbers. How can this be done? For loop
makes it quite easy for you.
Code:
int main()
{
int x,y,num,sum = 0;
scanf("%d %d",&x,&y);
for(num = x; num <= y; num++)
sum = sum + num;
printf("Summation of %d to %d is %d",x, y, sum);
}
You can use multiple variables for loop control. Initialization,
condition and update, every block can work with multiple
variables.
 In initialization and update, separate the two variable using
coma(,) separation.
 In condition, use logical and, or (&&, ||) according to your need.
Why should multiple variables be used? Suppose two sprinters
x and y are there and speed of y is double of speed of x. They
are going to participate in a 30 meter sprint. x has started from
10 meters ahead of y. Who have won the race? In different
stages of race, what is their position? Their positions can be
obtained in the following manner:
Code:
int main()
{
int x,y;
for (x=10, y=0 ; x <= 30 && y <= 30 ; x++, y= y+2)
{
printf("%dt%dn",x,y);
}
return 0;
}
Nested for loop: You can use one for loop inside another. It is
called nested for loop. Basic syntax for nested for loop is:
Code:
for (initialization; condition; update)
{
for (initialization; condition; update)
{
statement(s);
}
}
The process to draw a triangle using nested for loop is given:
Code:
int main()
{
int i,j,rows;
printf("Enter the number of rows");
scanf("%d",&rows);
for(i=1;i<=rows;++i)
{
for(j=1;j<=i;++j)
{
printf("*");
}
printf("n");
}
return 0;
}
The number of rows have been assumed as 3. Then for every
row, inner loop executes i times. the simulation is given here:
Input 1 : i = 1, j = 1
Output: *
Input 2 : i = 2, j = 1, 2
Output: * *
Input 3 : i = 3, j = 1, 2, 3
Output: * * *
One of the uses of nested loops is for creating two dimensional
array or matrix. Initialization of any matrix is done using nested
for loop. Suppose you will make a row*col matrix. An example
is given below showing how to initialize and access it.
Code:
int mat[10][10];
int i,j,row,col;
printf("Enter order of matrix=");
scanf("%d%d",&row,&col);
printf("Enter Elements: ");
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
scanf("%d",&mat[i][j]);
}
}
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
printf("row[%d] col[%d]= %dn",i,j,mat[i][j]);
}
}
while Loop
While loop can be thought as repetition of if statement.It is also
known as pre- test loop as condition check is done before
execution of the block.
Here is the basic syntax of a while loop:
Code:
While(condition)
{
statement(s);
}
Everything that can be done using for loop can be done using
while loop also. Remember the program that printed 0 to 4
using for loop. Below a while loop implementation is given. It
will give basic understanding about while loop.
Code:
int main()
{
int i = 0;
while(i < 5)
{
printf("%d",i);
i++;
}
}
Here, initialization is before for loop. Updating loop control
variable is done inside loop.
While loop provides some advantages when number of iteration
is not known. Suppose, you will take input continuously from
keyboard until a negative value is given. Here, number of
iteration of the loop is unknown to you. How while loop handles
it is depicted here.
Code:
int main()
{
int num = 0;
while(num >= 0)
{
printf("Enter new number");
scanf("%d",&num);
}
}
You can use multiple conditions in while loop. Let us play a
guessing game. I will randomly pick a number from 1 to 20. You
will try to guess it. I will give you hints every time whether you
got it, or you should try smaller number, or greater number. I
will give you 5 chances. This can be done using while loop in
the following manner.
Code:
int main
{
int secretNum, guessNum = 0;
int usedChance = 0;
int maxChances = 5;
srand((unsigned int)time(NULL));
secretNum = rand() % 20 + 1;
printf("Guess a number from 1 to 20.You will get %d
chancesn",maxChances);
while(guessNum != secretNum && usedChance < maxChances )
{
scanf("%d",&guessNum);
if(guessNum == secretNum)
printf("Congrats.You have got it.n");
else if(guessNum < secretNum)
printf("Try a bigger number.n");
else
printf("Try a smaller number.n");
usedChance++;
}
return 0;
}
You might change it slightly. Do not limit the chance to 5 times.
Give unlimited chances until the right number is guessed. Look
how many chance one player needs to get the number. Do it
yourself.
Like nested for loop, while loop also has nested version. Basic
syntax is:
Code:
while (condition1)
{
while (condition2)
{
statement(s);
}
}
Remember the for loop section. There was a matrix operation
using nested for loop. Matrix can also be initialized using
nested while loop.
Code:
i =0;
while(i < row)
{
j = 0;
while(j < col)
{
scanf("%dt",&mat[i][j]);
j++;
}
i++;
}
Similarly the value of matrix can be accessed.
do while Loop
do-while loop is a variation of while loop. The condition is
checked by a while loop and statements are in do segment. It is
also known as post-test tool as it first executes the block and
then checks the condition.
Here is the basic syntax :
Code:
do{
statement(s);
}while(condition);
Look at some comparison between while and do while.
 While loop first checks the condition, if the condition is satisfied,
then the statements are executed. In other hand, do-while loop
first executes statements one time and then check the
conditions for the next iteration.
 In while loop, it is possible that statements inside loop will not
be executed entirely, if condition fails for the very first time. On
the other hand, statements in do-while loop will be executed at
least one time.
The iteration of a do while loop is as below.
Code:
int max = 5;
int i = 0;
do{
i++;
printf("%dn",i);
}while(i < max);
The program prints the value from 1 to 5. In do segment, it
increments the loop control variable and print the value. In
while section, it checks if the value of loop control variable is
less than another variable.
Remember any game or application which shows you the menu
and allows you to select any option. Then according to your
choice, does some operation. For example, some menu like
this:
Select any one from the menu:
1. Add numbers.
2. Subtract numbers
3. Multiply numbers.
4. Divide numbers.
5. Exit.
You then make a choice from 1-5 and program works
accordingly. Look, at the beginning of the program, menu has
been displayed to you once. That means it is independent of
your choice of operation. Here lies the usage of do section of
do-while loop.
Code:
int option = -1;
float num1, num2;
do
{
printf("Enter two numbers");
scanf("%f %f",&num1,&num2);
printf("Select 1-5 for any operationn");
printf("1.Additionn");
printf("2.Subtractionn");
printf("3.Multiplicationn");
printf("4.Divisionn");
printf("5.Exit Programn");
scanf("%d", &option);
printf("n");
switch(option)
{
case 1:
printf("Summation result is =%.2fn",num1+num2);
break;
case 2:
printf("Subtraction result is =%.2fn",num1-num2);
break;
case 3:
printf("Multiplication result is
=%.2fn",num1*num2);
break;
case 4:
printf("Division result is =%.2fn",num1/num2);
break;
case 5:
printf("Terminating...");
break;
default:
printf("Invalid operator");
break;
}
}while(option != 5);
Every time you enter two numbers, program shows you the
menu. You can choose 1-4 to make the calculation and 5 to
exit. If you choose any other option other than 1-5, it prompts
you that you have choosen the invalid operator and redirects
you to the main menu again. The program continues until the
exit option, that means option 5 is pressed.
goto
goto statement performs unconditional jump from one
statement to another statement.But the this jump can be done
in the same function, you can not use goto statement to jump
from one function to another function.
Basic syntax for goto is as follows.
Code:
statement;
. . .
goto label;
statement;
label:
statement;
For more clarification, the example below shows depending on
conditional statement, how different label is executed and some
statements are ignored.
Code:
if(player1Runs > player2Runs)
goto player1
else
goto player2
. . .
. . .
player1:
printf(“I am player1, I have won the match”);
player2:
printf(“I am player2, I have won the match”);
Here, if player1Runs is greater than player2Runs, it jumps to
player1 label, otherwise jumps to player2 label using goto
statement.
You can use goto statement for looping. Instead of using for,
while, do while loop, you can do the same job using goto. An
example is shown below:
Code:
int i = 0;
firstLoop:
printf("%d",i);
i++;
if(i<10)
goto firstLoop;
printf("nout of first loop");
It is suggested not to use goto statements. The goal you
achieve by using goto statement, can be achieved more easily
using some other conditional statements like if-else if-else etc.
Shortcomings of goto statement:
 Make a mess of sequence of code
 Unintended infinite loop
 Reduces readability
So, we have had a journey through the different kinds of loop.
For long and repetitive task, loop is still the best logic structure.
According to the situation, you may have to choose one which
works best in that situation. So, start your practice and do the
best use of loops in your programs.
Custom Data Types in C - struct,
union and typedef
Contributed by faribasiddiq () On 2nd January, 2014
This is an article on Custom Data Types in C - struct, union
and typedef in C.
There are many built in data types in C. But sometimes, the
built in data types are not enough to perform the required tasks.
In that case, some custom data type can be built to meet the
necessary requirements. In this tutorial, the following custom
data types are going to be discussed:
 Structure
 Union
 Typedef
Structure
Structure is the most commonly used custom data type. When
you need to work with different variables of different data types
(i.e. char, int, float ) for a specific task, you have to use
structure.
Prototype:
Code:
struct tag
{
dataType member 1;
.....
.....
dataType member n;
};
Example:
Suppose an office has to make a list of all employees’
information in the office and employee information consists of
employee name, designation, department, age and salary. For
performing the task, a structure named employee may be
declared which consists of the required information.
Code:
struct employee
{
char name[50];
char designation[50];
char dept[50];
int age;
float salary;
};
Different section of structure: definition
Every structure consists of three parts:
1. The keyword struct
2. Tag
3. Members of structure
1) struct keyword:
If the example above is considered, structure starts with the
keyword struct. By this keyword, compiler is informed that a
custom data type of structue is going to be declared.
2) Tag:
It is generally the name of new data type. If the previous
structure is considered, the tag is employee. It informs that the
following structure will be used for employee.
3) Members:
Structure members are grouped in a curly braces after the tag
part. All the members which are needed to build the new data
type are listed here. In previous example, new custom data
type employee consists of name, designation, department, age
and salary. These members are grouped along with their data
type after the tag part.
Variable declaration:
The prototype of declaring a structure variable is as follows:
Code:
struct tag var1;
For the above example, you need to declare a variable like
below:
Code:
struct employee john;
Here, struct employee is data type; john is variable of this data
type. If more than one variable is required to declare, the code
would be this way:
Code:
struct employee john, josheph;
You can declare structure variable while declaring the structure.
Code:
struct employee
{
char name[50];
char designation[50];
char dept[50];
int age;
float salary;
} john, joseph;
Access and initialize member of a structure:
Consider another structure named birthDate. You need to keep
this structure in mind for the upcoming examples. Different
operations are going to be discussed using this structure.
Code:
struct birthDate
{
int day;
int month;
int year;
};
Here, day, month and year are members of the structure
birthdate. But how can these members be accessed and
initialized? The way to access the default data types would be
like below:
Code:
struct birthDate
{
int day;
int month;
int year;
};
int main()
{
day = 1;
month = 1;
year = 1980;
printf("%d-%d-%d",day,month,year);
}
The program returns following error:
Code:
Error 1 error C2065: 'day' : undeclared identifier
Error 2 error C2065: 'month' : undeclared identifier
Error 3 error C2065: 'year' : undeclared identifier
Error 4 error C2065: 'day' : undeclared identifier
Error 5 error C2065: 'month' : undeclared identifier
Error 6 error C2065: 'year' : undeclared identifier
So the structure members cannot be accessed like built in data
types. The solution is to declare a structure member at first,
then to use dot(.) operator to access each member.
Code:
int main()
{
struct birthDate johnBirthDate;
johnBirthDate.day = 1;
johnBirthDate.month = 1;
johnBirthDate.year = 1980;
printf("%d-%d-
%d",johnBirthDate.day,johnBirthDate.month,johnBirthDate.year);
}
Here, structure birthDate member johnBirthDate is declared.
Then, structure member is accessed using dot operator with
this variable.
More ways to initialize structure variable:
Code:
struct birthDate
{
int day;
int month;
int year;
}johnBirthDate = {1,1,1980};
Code:
struct birthDate
{
int day;
int month;
int year;
};
struct birthDate johnBirthDate = {1,1,1980};
Data passing among structure members:
One member’s value of a structure to another member can be
copied or assigned. The example given below will clarify the
scenario:
Code:
int main()
{
struct birthDate johnBirthDate;
johnBirthDate.day = 5;
johnBirthDate.month = johnBirthDate.day;
johnBirthDate.year = 1980;
printf("%d-%d-
%d",johnBirthDate.day,johnBirthDate.month,johnBirthDate.year);
}
Here the statement: johnBirthDate.month = johnBirthDate.day
copies data of structure member day to structure member
month.
Array vs Structure:
Arrays in C work with group of variable. For example,
Code:
int employee[10];
Here, employee is an array of ten integer variables. But the
thing is, only integer value in these ten variables can be stored.
But one integer value is not enough to store employee
information as it is necessary to store employee name,
designation, department, age and salary for each employee.So
we need a group of these variables.
Code:
char name[50];
char designation[50];
char dept[50];
int age;
float salary;
The concept of structure comes into action. Unlike array which
groups similar data types, a structure is for different data types.
Array of structure
Till now, it has been discussed how to declare a variable of any
structure and initialize the structure members using structure
variable. What would you do if you need array of structure? For
example, consider a situation where a database of all students
of a class needs to be created. In this case, an array of a
structure of student would be helpful.
Code:
struct student
{
char* name;
int id;
};
If you need to declare a variable of the structure , the way is:
Code:
struct student john;
If you need to declare an array of this structure , the way is:
Code:
struct student CSE[100];
Initialization Structure Array
Code:
struct student CSE[3] = {
"John",101,
"Joseph", 108,
"Maria",209
};
struct student CSE[3]= {
{"John",101},
{"Joseph", 108},
{"Maria",209}
};
Access structure array elements:
An initialized array of structure has been declared. The
demonstration below shows how to access the members.
Code:
int main()
{
int loopCount;
printf("Database of CSE studentsn");
printf("NametIdn");
printf("---------------n");
for(loopCount = 0; loopCount < 3; loopCount++)
{
printf("%st%dn",CSE[loopCount].name, CSE[loopCount].id);
}
}
The way to access the member of the structure goes this way:
CSE[loopCount].name and CSE[loopCount].id. Therefore, the
way to access is :
Code:
Structure tag[arrayIndex].structure_member
Pointer to Structure:
A pointer to a structure can also be defined. The following
structure gives demonstration:
Code:
struct birthDate
{
int day;
int month;
int year;
};
struct birthDate *johnBirthDate;
It means johnBirthDate is a pointer of birthDate structure.
Initialization:
The way to initialize a pointer of a structure is slightly different.
At first, memory for the pointer needs to be allocated. The size
of the allocated memory is equal to the size of structure.
Code:
johnBirthDate = malloc(sizeof *johnBirthDate);
Access structure member using pointer:
When a pointer to a structure is declared, the structure
members are accessed using arrow(->) operator, instead of
dot(.) operator. Here is an example of whole process.
Code:
struct birthDate
{
int day;
int month;
int year;
};
int main()
{
struct birthDate *johnBirthDate;
johnBirthDate = malloc(sizeof *johnBirthDate);
johnBirthDate->day = 1;
johnBirthDate->month = 1;
johnBirthDate->year = 1980;
printf("%d-%d-%d",johnBirthDate->day,johnBirthDate-
>month,johnBirthDate->year);
}
Everything is exactly same as the way structure variable works.
The differences are – memory allocation, and use of arrow(->)
operator instead of dot(.).
Nested Structure:
A structure can be declared as a member of another structure.
The following structure clarifies the issue:
Code:
struct employee
{
int empId;
char gender;
float salary;
};
It is assumed that the salary is not fixed for every employee. It
depends on the working hours and salary per hour. So another
structure for salary has to be declared.
Code:
struct salary{
int workingHour;
float salaryPerHOur;
};
Therefore, employee structure contains another structure
named salary.
Code:
struct employee{
int empId;
char gender;
struct salary{
int workingHour;
float salaryPerHOur;
}employeeSalary;
}myEmployee;
Here, employeeSalary is a variable of salary structure and
myEmployee is a variable of employee structure.
How will be the members of a inner structure accessed? The
way is:
Code:
OuterStructure.InnerStructure.InnerStructureMember;
So, if it is needed to access workingHour and salaryPerHour of
salary structure, then the way would be like this:
Code:
myEmployee.employeeSalary.workingHour;
myEmployee.employeeSalary.salaryPerHour;
Passing Structure as function Parameters:
A structure variable can be sent to a function and structure can
also be returned from function.
Code:
struct student
{
char* name;
int id;
};
void showStudentInfo(struct student st)
{
printf("Student Name: %sn",st.name);
printf("Student Id: %dn",st.id);
}
int main()
{
struct student student1;
student1.name = "John Richards";
student1.id = 109;
showStudentInfo(student1);
}
In the above example, a variable of student structure student1
is created in main funciton. Then its members name and id are
initialized. Next the structure variable student1 is sent to
showStudentInfo function. The function recieves the variable
with struct student datatype. Then the members of the structure
cen be accessed from showStudentInfo structure.
If the structure variable is passed to a function and the structure
member value is changed, does it affect the caller function?
Code:
struct student
{
char* name;
int id;
};
void showStudentInfo(struct student st)
{
st.name = "J. Richards";
st.id = 110;
printf("After changing valu in showStudentInfon");
printf("Student Name: %sn",st.name);
printf("Student Id: %dn",st.id);
}
int main()
{
struct student student1;
student1.name = "John Richards";
student1.id = 109;
showStudentInfo(student1);
printf("Back to main functionn");
printf("Student Name: %sn",student1.name);
printf("Student Id: %dn",student1.id);
}
The ouput would be like this.
Code:
After changing valu in showStudentInfo
Student Name: J. Richards
Student Id: 110
Back to main function
Student Name: John Richards
Student Id: 109
So, if any structure variable is passed to any function, a local
copy of that variable is made for that function. Any change of
the variable in that function is limited to only that function.
The scope of members of structure can be extended. The
following example would elucidate:
Code:
struct student
{
char* name;
int id;
};
void showStudentInfo(struct student* st)
{
st->name = "J. Richards";
st->id = 110;
printf("After changing valu in showStudentInfon");
printf("Student Name: %sn",st->name);
printf("Student Id: %dn",st->id);
}
int main()
{
struct student student1;
student1.name = "John Richards";
student1.id = 109;
showStudentInfo(&student1);
printf("Back to main functionn");
printf("Student Name: %sn",student1.name);
printf("Student Id: %dn",student1.id);
}
Whats are the changes? The address of student1 variable has
been passed to showStudentInfo function, it has been received
with a structure pointer in that function and the value has been
edited.
The output generated will be:
Code:
After changing valu in showStudentInfo
Student Name: J. Richards
Student Id: 110
Back to main function
Student Name: J. Richards
Student Id: 110
Values have been changed in showStudentInfo function. After
returning to the main funciton, the changed value of the
members is got.
Structure Memory Allocation:
A structure is considered like this:
Code:
struct employee{
int empId;
char gender;
float salary;
}emp1;
How many bytes will be allocated for emp1? Size of a structure
variable in memory is equal to the total size of all members of
the structure.
The structure employee consists of one char, one int and one
float member. If the size of int, char and float are 2,1 and 4
bytes individually, then total size of emp1 variable is = 2 + 1 + 4
= 7 bytes.
Union
Union is another commonly used custom data type beside
struct. Besides, it provides some benefits on memory issue
which structure does not provide. The details are discussed
below:
Prototype:
Code:
union tag
{
member 1;
...
....
member n;
};
Example:
Suppose, you need to create a union of all employees’
information in an office .
Code:
union employee
{
char name[50];
char designation[50];
char dept[50];
int age;
float salary;
};
Declaration of union is like structure except the keyword. The
keyword is union for declaring a union while for structure, the
keyword is struct.
Variable declaration:
It is also like structure variable declaration. Just the union
keyword needs to be used instead of struct.
Code:
union employee myEmployee;
It can also be done while declaring the structure.
Code:
union employee
{
char name[50];
char designation[50];
char dept[50];
int age;
float salary;
}myEmployee;
Access and initialize member of a union
This procedure is just same as the structure. Your concepts
would clarifies if you go through structure carefully.
Structure vs union
The job which can be performed by union, can also be done by
structure. So why should be union used?
The reason lies in the memory consumption. The memory
required for union is less than structure in most of the cases.
The clarification is given with a structure and union with same
members.
Code:
struct employee{
int empId;
char gender;
float salary;
}myEmployee;
union employee{
int empId;
char gender;
float salary;
}myEmployee;
Here, a structure and a union are declared both consisting of
same members.
Let us assume that memory consumption of int = 2 bytes, char
= 1 byte, float = 4 byte. In structure, total memory consumption
= 2 +1 +4 = 7 bytes. In union, total memory consumption is 4
bytes. How is that possible?
Union works in this concept: In some conditions, more than one
variable is needed actually,but all the variables do not work at
the same time. So the memory units needed to store the
member that takes the maximum unit of memory can be taken
and reused for other members.
In the above example, out of three members of union, float data
type takes most memory which is 4 bytes.
Typedef
It is a way of renaming built in data type(char, int) as well as
custom data type(struct, union). So, for this union, 4 bytes
memory is allocated and reused for other members when
needed.
Prototype:
Code:
typedef dataType newName;
Example:
Code:
typedef char word;
Here you would typedef the char data type to word. Now you
can declare any char type data using word keyword instead of
char.
So, if you write:
Code:
word ch;
It means the same with:
Code:
char ch;
typedef for built in data type:
You can typedef built in data types (i.e. int, float). For example:
Code:
typedef int Int16;
typedef float F32;
Then you can declare variable like this:
Code:
Int16 age, id;
F32 salary;
Typedef custom data type:
It is possible to typedef the custom data type(structure, union,
enumeraton)as well as built in data type.
Typedef Structure:
The birthDate structure is considered.
Code:
struct birthDate
{
int day;
int month;
int year;
};
You can typedef it to another name(Date).
Code:
typedef struct birtDate Date;
Then a variable using new name(Date) needs to be declared.
Code:
Date joiningDate;
Typedef Union:
To typedef union, the procedure is same as the structure.
Code:
union birthDate
{
int day;
int month;
int year;
};
typedef union birtDate Date;
Date joiningDate;
Typedef Enumeration:
Consider the following enumeration of color .
Code:
enum color{Red,Green,Blue};
You can typedef it to another name.
Code:
typedef enum color Color;
Then the new name of the enum is to be udes to declare
variable.
Code:
Color ball, leaf, sky;
C Functions
Contributed by msfq17a () On 30th December, 2013
This is an article on C Functions in C.
Function is a block of statements that performs a specific task.
It is reusable portion of the code and a very effective way to
modularize your program.
For example, you may need to perform different arithmetic
operations in your program like addition, subtraction,
multiplication and division. To implement it in a modular way,
you can define four different functions to perform this individual
task.
There are two type of functions:
1. Library function
2. User defined function
1. Library function:
Every language is accompanied by a collection of library
function which is used to perform some common, frequently
used operations. For example, we have seen the frequent use
of printf() and scanf() function in our C programs. These two
are library functions of C and are defined in header file stdio.h.
Code:
#include <stdio.h>
int main()
{
printf("Hello world");
}
2. User defined function:
Sometimes we need to modularize our program according to
our requirement, which is not available in library. So, we need
to define function ourselves, which is called user defined
function. For example, you may want to greet user at the start
of the program. This is how you can do this:
Code:
void greeting()
{
printf("Hello Friend");
}
int main()
{
greeting();
return 0;
}
Parts of Function
1. Function prototype
2. Function definition
3. Function call
1. Function prototype:
Code:
dataType functionName (parameter list)
Example of function prototype:
Code:
void func()
int func()
void func(int )
int func(int , int )
Explanation for each is provided as follows:
void func() - You cannot return any value from this function to
caller function, as return type is void. If you try to return any
value, error will occur. No parameter can be received by this
function, as parameter list is empty.
int func() You can return only integer value from this function to
caller function. Trying to return value of any other data type will
cause some error. No parameter can be received by this
function, as parameter list is empty.
void func(int a) - Look at the parameter in the function. It means
the function receives one parameter, the data type of which is
integer. While calling this function, you must send only one
parameter of integer type. This function returns no value to the
caller.
int func(int , int ) - You can send more than one parameter
while calling a function. Look at the function stated above. It
receives two parameter of type integer. It also returns an
integer value to the caller function.
double func(int , double) - You can send different types of
parameter in one function. In the above function, two
parameters can be received. The first one should be of integer
type and second one of double type. After doing all operations,
according to prototype of this function, a double value must be
returned to the caller function.
2. Function definition:
Function definition is the body of the function.
Code:
void greeting()
{
printf("Hello Friend");
}
Here, void greeting() is the prototype of the function. Function
body is the statement(s) between two curly braces{}.
3. Function call
You can call a function by function name and parameter list,
like this:
Code:
functionName(parameter1,…parameterN)
Function calling statement must match with the function
prototype.
Function Parameters
When a function is called with parameter(s), it can pass the
parameters in two way:
1. By Value
2. By pointer
1. By Value
In this type of calling, called function get the value of
parameters from caller function and receive it with some
variable. This variable works like local variable for the called
function. So, any changes made in this variable is valid only for
the called function, the caller does not get the change.
Code:
void changeVal(int a,int b)
{
if(a >= b)
b = 0;
else
a = 0;
}
int main()
{
int x,y,bigger;
printf("Enter x:");
scanf("%d",&x);
printf("Enter y:");
scanf("%d",&y);
changeVal(x,y);
printf("After returning from changeVal function:n");
printf("x = %d, y = %d",x,y);
}
Output:
Code:
Enter x:25
Enter y:40
After returning from changeVal function:
x = 25, y = 40
In the above example, changeaVal function get called from
main function with x and y value. This values are received by
changeaVal with variable a and b. Then values of this variable
get changed by changeaVal . But after returning to main
function, value of x and y remains the same. The changes
made by changeaVal function are local to this function.
2. By Pointer
In this type of calling, called function gets the memory of
parameters from caller function and receives it with some
pointers to that addresses. So, when any change is made,
value of the memory address gets changed. So, the caller
function also gets the effect of changed value.
Code:
void changeVal(int *a,int *b)
{
if(*a > *b)
*b = 0;
else
*a = 0;
}
int main()
{
int x,y,bigger;
printf("Enter x:");
scanf("%d",&x);
printf("Enter y:");
scanf("%d",&y);
changeVal(&x,&y);
printf("After returning from changeVal function:n");
printf("x = %d, y = %d",x,y);
}
Output:
Code:
Enter x:25
Enter y:40
After returning from changeVal function:
x = 0, y = 40
Here we can see that main function also get the changes which
is made by changeVal function.
Nested function call
Sometimes while one function calls another one, the called
function also calls another function to perform its task. It works
like this:
The example given below illustrates the whole picture. Here,
main function calls the getArea function. But to calculate area,
you need to know length and width. So, before returning to
main , getArea calls getLength and getWidth. getLength and
getWidth function individually returns length and width to
getArea function. getArea then calculates the area and returns
the area to main .
Code:
int getWidth()
{
int wd=0;
printf("Enter width:");
scanf("%d",&wd);
return wd;
}
int getLength()
{
int len =0;
printf("Enter length:");
scanf("%d",&len);
return len;
}
int getArea()
{
int length, height =0;
length = getLength();
height = getWidth();
return length*height;
}
int main()
{
int area;
area = getArea();
printf("Area is: %d",area);
}
Return from function:
By executing return statement, execution returns from the
called function to caller function. If there are multiple return
statements, only one out of them is executed and the rest are
ignored.
Code:
int getBigger(int a,int b)
{
if(a > b)
return a;
else
return b;
}
int main()
{
int x,y,bigger;
printf("Enter x:");
scanf("%d",&x);
printf("Enter y:");
scanf("%d",&y);
bigger = getBigger(x,y);
printf("bigger num is: %d",bigger);
}
Here, in getBigger function, we can see two return statements.
When any return statement is executed, no other statements
are executed. Execution returns to the caller.
Recursive function
When a function is called by itself, then it is called recursive
function. Recursive function has two parts:
1. Base case
2. Recursive case
General concept of recursive function is like this: it will call itself
with some parameters until the base case is true.
Code:
int recursiveAdd(int num)
{
if(num < 1)
return num;
else
return (num+recursiveAdd(num-1));
}
int main()
{
int input, sum = 0;
printf("Enter number: ");
scanf("%d",&input);
sum = input + recursiveAdd(input-1);
printf("Sum of number from 1 to %d is %d",input,sum);
}
The base case is:
Code:
if(num < 1)
return num;
And the recursive case is:
Code:
else
return (num+recursiveAdd(num-1));
As long as the number is greater or equal to 1, the function
continues to call itself. When the number is less than 1, then
base case is executed the recursion is stopped.
Most popular example of recursive function is to find out the
factorial.
Code:
int getFactorial(int num)
{
if(num <= 1)
return 1;
else
return (num * getFactorial(num-1));
}
int main()
{
int input, factorial = 0;
printf("Enter number: ");
scanf("%d",&input);
factorial = input * getFactorial(input-1);
printf("Factorial of number %d is %d",input,factorial);
}
Infinite recursion:
What if any recursive function doesn’t have any base case?
Code:
int recursiveFunc(int num)
{
recursiveFunc(num-1);
}
Here, no base case exists for recursiveFunc. So every time it is
called by itself, it never exits. It results an infinity loop.
Another scenario: Let, you wrote a base case that will never be
executed. What will happen?
Code:
int recursiveFunc(int num)
{
if(num < 1)
return num;
else
recursiveFunc(num+1);
}
int main()
{
int input, result = 0;
printf("Enter number: ");
scanf("%d",&input);
result = recursiveFunc(input-1);
}
If user gives a positive number as input, what will happen? In
recursiveFunc, an integer with positive value will be passed.
First time, base case will be false, so it will make a recursive
call with(n+1). And if you have a closer look, every time the
value of parameter will be increased by 1. So it will never be
less than 1. Every time the base case fails, results an infinite
recursion.
Direct and indirect recursion:
When a function calls itself, it is called direct recursion. But if
two function individually call one another, what will happen?
Code:
int getX()
{
getY();
}
int getY()
{
getX();
}
Here, getX() calls getY(). When execution comes in getY(), it
again calls getX(), and getX() calls getY(). This process
continues, resulting an recursion. Sometimes, this type of
indirect recursion also results an infinite recursion.
Benefits of using function:
1. Program can be modularized into small parts
2. Different function can be independently developed according to
the requirement
3. Increases readability and re-usability
C Arrays
Contributed by msfq17a () On 30th December, 2013
This is an article on C Arrays in C.
Array is a data structure consists of a group of elements of
same data type. We can think it as collection of variable of
similar data type.
Array prototype:
Code:
Data_type array_name[array_size]
Example:
Suppose you have a team of 10 employees. Id is given for
every employee. You want to store id, age and salary of each
employee. How will you do that? From the concept of variable,
you can declare 10 variables to store individual id, like:
intemployeeId0, employeeId1, employeeId2, employeeId3,
employeeId4, employeeId5, employeeId6, employeeId7,
employeeId8, employeeId9;
Isn’t that a hazard? You are declaring ten variables only for
storing ten ids.
It is the case where array facilitates you. Instead of ten
variables, you can declare only one variable and store the
same type of data in it.
Code:
int employeeId[10];
Here, employeeId is an array of integer type of size 10.
Array Indexing:
So, if array is able to address different data of same type with
same variable name, how does it maintain it? Indexing does the
task. For the array declared above, every employee id can be
accessed by the index of the array. The elements are:
employeeId[0], employeeId[1], employeeId[2], employeeId[3],
employeeId[4], employeeId[5], employeeId[6], employeeId[7],
employeeId[8], employeeId[9]
0,1,2…9 are the index of individual element. If the size of the
array is n, then the index of array elements are from 0 to n-1.
You can use array of age and salary of the employees as well.
Code:
int employeeAge[10], float employeeSalary[10]
Array Memory Allocation:
The whole array is stored in a single contiguous memory block.
Let, you have an array of integer:
Code:
int employeeId[10];
If size of an integer is 2 byte, then 20(10*2) bytes will be
required to store this array in memory and these 20 bytes must
be contiguous.
Address of the first element is called the base address of the
array. Address of ith element of the array can be achieved by
following formula:
Address of i element = Address of base + size of element * i;
Array initialization
There are different ways to assign values to elements of an
array .
 Static initialization
 Assigning values from Standard Input
 Default Array initialization
1. Static initialization:
Code:
int employeeAge[10] = {35,30,30,30,28,28,25,34,35,40};
2. Assigning values from Standard Input:
Suppose you have an array for age of employee, int
employeeAge[10] . You want to take input and store the value
in the array. You can use for loop to initialize the array.
Code:
int employeeAge[10], count, totalScore = 0;
for(count = 0; count < 10; count++)
{
printf("Enter Age: employeeAge[%d]:", count);
scanf("%d",& employeeAge[count]);
}
3. Default Array initialization:
Code:
int main()
{
int arr [5] = {20};
int count;
for(count = 0; count < 5; count++)
{
printf("%dn", arr [count]);
}
}
Output:
Code:
20
0
0
0
0
Here, array size is 5. But we have initialized it with only one
value {20}, instead of five. So,
first element of the array, arr[0] get initialized with 20 and other
elements are initialized with 0.
Accessing array elements
Suppose you have an array, which is initialized. Now you want
to see the value of each element. Here is an example for doing
this stuff:
Code:
int main()
{
int count;
int employeeAge[10] = {35,30,30,30,28,28,25,34,35,40};
printf("here is the individual age of employees:n");
for(count = 0; count < 10; count++)
{
printf("employee[%d]: %dn", count,employeeAge[count]);
}
}
Passing Arrays to Function
There are two ways of doing this:
1. Array element as parameter
2. Whole array as parameter
1. Array element as parameter
If you want to send some element of an array to a function, you
can specify the elements by their index. In the example given
below, 1st and 2nd element of the array byteVal[8] are sent to
addVal function. The parameters are byteVal[0] and byteVal[1].
Accordiingly, 2nd and 5th element of byteVal[8] array are sent
to subtractVal function.
Code:
int addVal(int x, int y)
{
int sum = x+y;
return sum;
}
int subtractVal(int x, int y)
{
int sub = x - y;
return sub;
}
int main()
{
int byteVal[8] = {40,10,250,5,190,150,80,200};
int addByteVal, subByteVal;
addByteVal = addVal(byteVal[0],byteVal[1]);
subByteVal = subtractVal(byteVal[1],byteVal[4]);
printf("addition result : %d, subtraction result: %d",addByteVal,
subByteVal);
}
2. Whole array as parameter
So, when you want to call a function with an array as argument,
just write the array name. The parameter passing procedure is
just like the variable passing. The difference is in how the called
function receives the array. To receive an array, you have to
write the array name with array notation[]. It means that the
received parameter is an array. You do not need to define the
array size here.
In the example given below, array byteVal is passed to the
function showByteVal by only the name and received with an
integer array, int getByte[] .
Code:
int showByteVal(int getByte[])
{
int count;
printf("Array of byte value recieved. Values are:n");
for(count = 0; count < 8; count++)
{
printf("%dn",getByte[count]);
}
}
int main()
{
int byteVal[8] = {40,10,250,5,190,150,80,200};
showByteVal(byteVal);
}
Why array passed to function changes its value?
Suppose you send an array or any array elements to a function.
Then you make some operation on the array elements and
change value of the element. When the function returns, the
data passed as array parameter is changed. Let’s see:
Code:
int changeByteVal(int getByte[])
{
int count;
printf("Array of byte value recieved. Values are:n");
for(count= 0; count < 8; count++)
{
printf("%dn",getByte[count]);
}
getByte[0] = getByte[1] + getByte[2];
}
int main()
{
int loopCount;
int byteVal[8] = {40,10,250,5,190,150,80,200};
changeByteVal(byteVal);
printf("returned from changeByteVal function. Now values are:n");
for(loopCount= 0; loopCount < 8; loopCount++)
{
printf("%dn",byteVal[loopCount]);
}
}
Output:
Code:
Array of byte value received. Values are:
40
10
250
5
190
150
80
200
returned from changeByteVal function. Now values are:
260
10
250
5
190
150
80
200
In the above program the first element of byteVal array,
byteVal[0] is initialized with value 40. The array is sent to
changeByteVal function. Here, value of byteVal[0] has been
changed to 260. When we return to caller function, we print the
element of the array and experience that value of byteVal[0] is
now 260.
When an array is sent to a function, it is the base address of
the array is sent. The base address received by the called
function makes operation on the variables memory and so the
original value gets changed. So, you will always get the
changed value.
2D Arrays
Array can be multi dimensional. In this section, we will discuss
about two-dimensional array.
Prototype:
Prototype of 2d array is:
Code:
DataType arrayName [rowSize][columnSize]
Think of an array of 2*2 dimension. It is declared as:
Code:
int matrix[2][2];
Visualization is like this:
Elements of this 2d array are:
Code:
matrix[0][0] = 0
matrix[0][1] = 1
matrix[1][0] = 2
matrix[1][1] = 3
Suppose you have three teams and every team contains five
members. You want to store the age of each member of every
team. Then you should declare a two dimensional array of 3*5
size.
int memberAge[3][5]
Here, 3 is team number and 5 is number of members of every
team. You can initialize and access age of each member of
each team by this 2d array.
2D Array Initialization
2d array is initialized in the same ways as array.
1. Static initialization
2. Assigning values from Standard Input
3. Default Array initialization
1. Static initialization:
2d array can be statically initialized in 2 different ways:
Way 1: int age[2][3]= {40,35,30,42,33,25};
Way 2: int age[2][3] = {{40,35,30},{42,33,25}};
2. Assigning values from Standard Input:
How to initialize every element of a 2d array from standard
input? Let’s see:
Code:
#define ROWSIZE 2
#define COLSIZE 3
int main()
{
int row, col;
int age[ROWSIZE][ COLSIZE];
for(row = 0; row < ROWSIZE; row++)
for(col =0; col < COLSIZE; col++)
scanf("%d",&age[row][col]);
}
3. Default Array initialization
This is same as single dimension array where the specified
values are initialized and rest is all 0.
Accessing 2d array elements
If you have an initialized 2d array and want to get the values,
you can act like this:
Code:
#define ROWSIZE 2
#define COLSIZE 3
int main()
{
int row, col;
int age[ROWSIZE][ COLSIZE] = {40,35,30,42,33,25};
for(row = 0; row < ROWSIZE; row++)
for(col =0; col < COLSIZE; col++)
printf("Index[%d][%d] :
%dn",row,col,age[row][col]);
}
Use of Arrays
Array is used for different operations. In some searching and
sorting algorithm, array is very important and useful. We are
going to watch how array facilitates linear search operation.
Linear search:
Let you have a list of roll numbers who have passed in the last
exam. Now, some students come to you, tell their rolls and ask
you whether they are in the pass list. The list is not sorted in
increasing or decreasing order yet. How will you search their
roll? For every student, you will start from the beginning of your
list and search every element of the list throughout the end. If
roll number is found, you will stop and tell that he/she has
passed. Otherwise you would inform the negative result. This
type of searching is called linear search.
Here is a way of implementing linear search using array:
Code:
#define SIZE 4
int main()
{
int i,searchNum;
int arrayOfNum[SIZE];
int flag = 0;
int iterate = SIZE - 1;
printf("Enter %d elements of array:n",SIZE);
for(i =0; i < SIZE; i++)
{
printf("narrayOfNum[%d]:",i);
scanf("%d",&arrayOfNum[i]);
}
printf("Enter the element you want to search:");
scanf("%d",&searchNum);
for(i = 0; i < SIZE; i++)
{
if(arrayOfNum[i] == searchNum)
{
printf("%d found in arrayOfNum[%d]",searchNum,i);
flag = 1;
break;
}
}
if(flag == 0)
printf("Not foundn");
}
Use of 2d Array
2d array can be used for different advanced operations. Out of
them, most common example is matrix operation. We can
perform any matrix operation using 2d arrays. We are going to
explain matrix addition operation using 2d arrays.
Matrix Addition
Suppose A and B are two matrices. We have to perform matrix
addition and save the result in another matrix. Let the new
matrix is C. So, the operation we are going to perform is:
C = A + B.
Code:
#define ROWSIZE 2
#define COLSIZE 3
int main()
{
int row, col;
int A[ROWSIZE][COLSIZE],B[ROWSIZE][COLSIZE],C[ROWSIZE][COLSIZE];
printf("Enter elements of matrix A:n");
for(row = 0; row < ROWSIZE; row++)
for(col =0; col < COLSIZE; col++)
{
printf("nA[%d][%d]:",row,col);
scanf("%d",&A[row][col]);
}
printf("Enter elements of matrix B:n");
for(row = 0; row < ROWSIZE; row++)
for(col =0; col < COLSIZE; col++)
{
printf("nB[%d][%d]:",row,col);
scanf("%d",&B[row][col]);
}
printf("After performing operation C = A+B:n");
for(row = 0; row < ROWSIZE; row++)
for(col =0; col < COLSIZE; col++)
{
C[row][col] = A[row][col] + B[row][col];
printf("C[%d][%d] : %dn",row,col,C[row][col]);
}
}
Advantages of Arrays
1. Group of similar objects can be used by single variable and
different index.
2. Multi dimensional arrays is possible
3. Accessing array element is not sequential and so operations
like searching, sorting are faster.
Disadvantages of Arrays
1. Array size is static in C. Allocated memory cannot be increased
or decreased with arrays and so size of array has to to be
known before any operation. For dynamic size we have to be
using pointers.
2. Removing array elements from between means the complete
array needs to be shifted which is a costly operation.

More Related Content

What's hot

Process concept
Process conceptProcess concept
Process conceptjangezkhan
 
Input and Output In C Language
Input and Output In C LanguageInput and Output In C Language
Input and Output In C LanguageAdnan Khan
 
File Handling In C++(OOPs))
File Handling In C++(OOPs))File Handling In C++(OOPs))
File Handling In C++(OOPs))Papu Kumar
 
Presentation on c structures
Presentation on c   structures Presentation on c   structures
Presentation on c structures topu93
 
File Management in Operating System
File Management in Operating SystemFile Management in Operating System
File Management in Operating SystemJanki Shah
 
Introduction to CPU registers
Introduction to CPU registersIntroduction to CPU registers
Introduction to CPU registersMuhammad Waqas
 
Input Output Management In C Programming
Input Output Management In C ProgrammingInput Output Management In C Programming
Input Output Management In C ProgrammingKamal Acharya
 
Pointers in c language
Pointers in c languagePointers in c language
Pointers in c languageTanmay Modi
 
MCA-I-COA- overview of register transfer, micro operations and basic computer...
MCA-I-COA- overview of register transfer, micro operations and basic computer...MCA-I-COA- overview of register transfer, micro operations and basic computer...
MCA-I-COA- overview of register transfer, micro operations and basic computer...Rai University
 
file handling c++
file handling c++file handling c++
file handling c++Guddu Spy
 
OPERATING SYSTEMS DESIGN AND IMPLEMENTATION
OPERATING SYSTEMSDESIGN AND IMPLEMENTATIONOPERATING SYSTEMSDESIGN AND IMPLEMENTATION
OPERATING SYSTEMS DESIGN AND IMPLEMENTATION sathish sak
 
UNIT 10. Files and file handling in C
UNIT 10. Files and file handling in CUNIT 10. Files and file handling in C
UNIT 10. Files and file handling in CAshim Lamichhane
 

What's hot (20)

Process concept
Process conceptProcess concept
Process concept
 
Input and Output In C Language
Input and Output In C LanguageInput and Output In C Language
Input and Output In C Language
 
Data Types In C
Data Types In CData Types In C
Data Types In C
 
Know the UNIX Commands
Know the UNIX CommandsKnow the UNIX Commands
Know the UNIX Commands
 
File management
File managementFile management
File management
 
File Handling In C++(OOPs))
File Handling In C++(OOPs))File Handling In C++(OOPs))
File Handling In C++(OOPs))
 
Presentation on c structures
Presentation on c   structures Presentation on c   structures
Presentation on c structures
 
File handling
File handlingFile handling
File handling
 
File Management in Operating System
File Management in Operating SystemFile Management in Operating System
File Management in Operating System
 
Introduction to CPU registers
Introduction to CPU registersIntroduction to CPU registers
Introduction to CPU registers
 
Input Output Management In C Programming
Input Output Management In C ProgrammingInput Output Management In C Programming
Input Output Management In C Programming
 
Pointers in c language
Pointers in c languagePointers in c language
Pointers in c language
 
file
filefile
file
 
Assembler
AssemblerAssembler
Assembler
 
MCA-I-COA- overview of register transfer, micro operations and basic computer...
MCA-I-COA- overview of register transfer, micro operations and basic computer...MCA-I-COA- overview of register transfer, micro operations and basic computer...
MCA-I-COA- overview of register transfer, micro operations and basic computer...
 
Program execution
Program executionProgram execution
Program execution
 
string in C
string in Cstring in C
string in C
 
file handling c++
file handling c++file handling c++
file handling c++
 
OPERATING SYSTEMS DESIGN AND IMPLEMENTATION
OPERATING SYSTEMSDESIGN AND IMPLEMENTATIONOPERATING SYSTEMSDESIGN AND IMPLEMENTATION
OPERATING SYSTEMS DESIGN AND IMPLEMENTATION
 
UNIT 10. Files and file handling in C
UNIT 10. Files and file handling in CUNIT 10. Files and file handling in C
UNIT 10. Files and file handling in C
 

Viewers also liked

C programming notes BATRACOMPUTER CENTRE IN Ambala CANTT
C programming notes BATRACOMPUTER CENTRE IN Ambala CANTTC programming notes BATRACOMPUTER CENTRE IN Ambala CANTT
C programming notes BATRACOMPUTER CENTRE IN Ambala CANTTBatra Centre
 
What Makes Great Infographics
What Makes Great InfographicsWhat Makes Great Infographics
What Makes Great InfographicsSlideShare
 
Masters of SlideShare
Masters of SlideShareMasters of SlideShare
Masters of SlideShareKapost
 
STOP! VIEW THIS! 10-Step Checklist When Uploading to Slideshare
STOP! VIEW THIS! 10-Step Checklist When Uploading to SlideshareSTOP! VIEW THIS! 10-Step Checklist When Uploading to Slideshare
STOP! VIEW THIS! 10-Step Checklist When Uploading to SlideshareEmpowered Presentations
 
10 Ways to Win at SlideShare SEO & Presentation Optimization
10 Ways to Win at SlideShare SEO & Presentation Optimization10 Ways to Win at SlideShare SEO & Presentation Optimization
10 Ways to Win at SlideShare SEO & Presentation OptimizationOneupweb
 
How To Get More From SlideShare - Super-Simple Tips For Content Marketing
How To Get More From SlideShare - Super-Simple Tips For Content MarketingHow To Get More From SlideShare - Super-Simple Tips For Content Marketing
How To Get More From SlideShare - Super-Simple Tips For Content MarketingContent Marketing Institute
 
How to Make Awesome SlideShares: Tips & Tricks
How to Make Awesome SlideShares: Tips & TricksHow to Make Awesome SlideShares: Tips & Tricks
How to Make Awesome SlideShares: Tips & TricksSlideShare
 

Viewers also liked (11)

C programming notes BATRACOMPUTER CENTRE IN Ambala CANTT
C programming notes BATRACOMPUTER CENTRE IN Ambala CANTTC programming notes BATRACOMPUTER CENTRE IN Ambala CANTT
C programming notes BATRACOMPUTER CENTRE IN Ambala CANTT
 
C Language Unit-5
C Language Unit-5C Language Unit-5
C Language Unit-5
 
Pointers in C
Pointers in CPointers in C
Pointers in C
 
File handling in C
File handling in CFile handling in C
File handling in C
 
What Makes Great Infographics
What Makes Great InfographicsWhat Makes Great Infographics
What Makes Great Infographics
 
Masters of SlideShare
Masters of SlideShareMasters of SlideShare
Masters of SlideShare
 
STOP! VIEW THIS! 10-Step Checklist When Uploading to Slideshare
STOP! VIEW THIS! 10-Step Checklist When Uploading to SlideshareSTOP! VIEW THIS! 10-Step Checklist When Uploading to Slideshare
STOP! VIEW THIS! 10-Step Checklist When Uploading to Slideshare
 
You Suck At PowerPoint!
You Suck At PowerPoint!You Suck At PowerPoint!
You Suck At PowerPoint!
 
10 Ways to Win at SlideShare SEO & Presentation Optimization
10 Ways to Win at SlideShare SEO & Presentation Optimization10 Ways to Win at SlideShare SEO & Presentation Optimization
10 Ways to Win at SlideShare SEO & Presentation Optimization
 
How To Get More From SlideShare - Super-Simple Tips For Content Marketing
How To Get More From SlideShare - Super-Simple Tips For Content MarketingHow To Get More From SlideShare - Super-Simple Tips For Content Marketing
How To Get More From SlideShare - Super-Simple Tips For Content Marketing
 
How to Make Awesome SlideShares: Tips & Tricks
How to Make Awesome SlideShares: Tips & TricksHow to Make Awesome SlideShares: Tips & Tricks
How to Make Awesome SlideShares: Tips & Tricks
 

Similar to Understanding c file handling functions with examples

Similar to Understanding c file handling functions with examples (20)

Advance C Programming UNIT 4-FILE HANDLING IN C.pdf
Advance C Programming UNIT 4-FILE HANDLING IN C.pdfAdvance C Programming UNIT 4-FILE HANDLING IN C.pdf
Advance C Programming UNIT 4-FILE HANDLING IN C.pdf
 
Satz1
Satz1Satz1
Satz1
 
4 text file
4 text file4 text file
4 text file
 
Data Structure Using C - FILES
Data Structure Using C - FILESData Structure Using C - FILES
Data Structure Using C - FILES
 
Unit 5 dwqb ans
Unit 5 dwqb ansUnit 5 dwqb ans
Unit 5 dwqb ans
 
Chapter 13.1.10
Chapter 13.1.10Chapter 13.1.10
Chapter 13.1.10
 
Unit5 C
Unit5 C Unit5 C
Unit5 C
 
File handling-c
File handling-cFile handling-c
File handling-c
 
C programming session 08
C programming session 08C programming session 08
C programming session 08
 
Unit 8
Unit 8Unit 8
Unit 8
 
File Handling in c.ppt
File Handling in c.pptFile Handling in c.ppt
File Handling in c.ppt
 
file handling1
file handling1file handling1
file handling1
 
Module 5 file cp
Module 5 file cpModule 5 file cp
Module 5 file cp
 
file_handling_in_c.ppt
file_handling_in_c.pptfile_handling_in_c.ppt
file_handling_in_c.ppt
 
Unit5
Unit5Unit5
Unit5
 
C Programming Unit-5
C Programming Unit-5C Programming Unit-5
C Programming Unit-5
 
file.ppt
file.pptfile.ppt
file.ppt
 
Handout#01
Handout#01Handout#01
Handout#01
 
Unit-VI.pptx
Unit-VI.pptxUnit-VI.pptx
Unit-VI.pptx
 
File in c
File in cFile in c
File in c
 

More from Muhammed Thanveer M

Easy check is simple and easy use lodge management system
Easy check is simple and easy use lodge management systemEasy check is simple and easy use lodge management system
Easy check is simple and easy use lodge management systemMuhammed Thanveer M
 
KeyBan....easy to think and work
KeyBan....easy to think and workKeyBan....easy to think and work
KeyBan....easy to think and workMuhammed Thanveer M
 
mysql ....question and answer by muhammed thanveer melayi
mysql ....question and answer by muhammed thanveer melayimysql ....question and answer by muhammed thanveer melayi
mysql ....question and answer by muhammed thanveer melayiMuhammed Thanveer M
 
Stored procedures by thanveer danish melayi
Stored procedures by thanveer danish melayiStored procedures by thanveer danish melayi
Stored procedures by thanveer danish melayiMuhammed Thanveer M
 
Statements,joins and operators in sql by thanveer danish melayi(1)
Statements,joins and operators in sql by thanveer danish melayi(1)Statements,joins and operators in sql by thanveer danish melayi(1)
Statements,joins and operators in sql by thanveer danish melayi(1)Muhammed Thanveer M
 
Udf&views in sql...by thanveer melayi
Udf&views in sql...by thanveer melayiUdf&views in sql...by thanveer melayi
Udf&views in sql...by thanveer melayiMuhammed Thanveer M
 
Functions with heap and stack....by thanveer danish
Functions with heap and stack....by thanveer danishFunctions with heap and stack....by thanveer danish
Functions with heap and stack....by thanveer danishMuhammed Thanveer M
 
Elements of c program....by thanveer danish
Elements of c program....by thanveer danishElements of c program....by thanveer danish
Elements of c program....by thanveer danishMuhammed Thanveer M
 
Aptitude model by thanveer danish
Aptitude model by thanveer danishAptitude model by thanveer danish
Aptitude model by thanveer danishMuhammed Thanveer M
 
Preprocesser in c++ by thanveer danish
Preprocesser in c++ by thanveer danishPreprocesser in c++ by thanveer danish
Preprocesser in c++ by thanveer danishMuhammed Thanveer M
 
Oop concept in c++ by MUhammed Thanveer Melayi
Oop concept in c++ by MUhammed Thanveer MelayiOop concept in c++ by MUhammed Thanveer Melayi
Oop concept in c++ by MUhammed Thanveer MelayiMuhammed Thanveer M
 

More from Muhammed Thanveer M (20)

Easy check is simple and easy use lodge management system
Easy check is simple and easy use lodge management systemEasy check is simple and easy use lodge management system
Easy check is simple and easy use lodge management system
 
KEYBAN...MODULES
KEYBAN...MODULES KEYBAN...MODULES
KEYBAN...MODULES
 
KeyBan....easy to think and work
KeyBan....easy to think and workKeyBan....easy to think and work
KeyBan....easy to think and work
 
Codeinator
CodeinatorCodeinator
Codeinator
 
mysql ....question and answer by muhammed thanveer melayi
mysql ....question and answer by muhammed thanveer melayimysql ....question and answer by muhammed thanveer melayi
mysql ....question and answer by muhammed thanveer melayi
 
Jvm
JvmJvm
Jvm
 
Transation.....thanveeer
Transation.....thanveeerTransation.....thanveeer
Transation.....thanveeer
 
Stored procedures by thanveer danish melayi
Stored procedures by thanveer danish melayiStored procedures by thanveer danish melayi
Stored procedures by thanveer danish melayi
 
Statements,joins and operators in sql by thanveer danish melayi(1)
Statements,joins and operators in sql by thanveer danish melayi(1)Statements,joins and operators in sql by thanveer danish melayi(1)
Statements,joins and operators in sql by thanveer danish melayi(1)
 
Udf&views in sql...by thanveer melayi
Udf&views in sql...by thanveer melayiUdf&views in sql...by thanveer melayi
Udf&views in sql...by thanveer melayi
 
Aptitude Questions-2
Aptitude Questions-2Aptitude Questions-2
Aptitude Questions-2
 
The basics of c programming
The basics of c programmingThe basics of c programming
The basics of c programming
 
Preprocesser in c
Preprocesser in cPreprocesser in c
Preprocesser in c
 
Functions with heap and stack....by thanveer danish
Functions with heap and stack....by thanveer danishFunctions with heap and stack....by thanveer danish
Functions with heap and stack....by thanveer danish
 
Elements of c program....by thanveer danish
Elements of c program....by thanveer danishElements of c program....by thanveer danish
Elements of c program....by thanveer danish
 
Aptitude model by thanveer danish
Aptitude model by thanveer danishAptitude model by thanveer danish
Aptitude model by thanveer danish
 
Preprocesser in c++ by thanveer danish
Preprocesser in c++ by thanveer danishPreprocesser in c++ by thanveer danish
Preprocesser in c++ by thanveer danish
 
Data base by thanveer danish
Data base by thanveer danishData base by thanveer danish
Data base by thanveer danish
 
Oop concept in c++ by MUhammed Thanveer Melayi
Oop concept in c++ by MUhammed Thanveer MelayiOop concept in c++ by MUhammed Thanveer Melayi
Oop concept in c++ by MUhammed Thanveer Melayi
 
Memory allocation in c
Memory allocation in cMemory allocation in c
Memory allocation in c
 

Understanding c file handling functions with examples

  • 1. Understanding C File Handling Functions With Examples Contributed by faribasiddiq () On 12th January, 2014 This is an article on Understanding C File Handling Functions With Examples in C. Data files are very essential part of in computer programming. The data we use while programming using the variables of different data types, are unavailable after the program execution. So,there is no way to retrieve the data if we further need. Here comes the necessity of data files.  FILE Structure  fopen  fclose  File Access Mode  fputs  fgets  fputc  fgetc  fprintf  fscanf  fwrite  fread  freopen  fflush  feof  fseek  ftell
  • 2.  fgetpos  fsetpos  rewind  perror  Binary files FILE Structure FILE is a structure that is used for data storage. The structure of FILE is: Code: typedef struct { int level; unsigned flags; char fd; unsigned char hold; int bsize; unsigned char_FAR* buffer; unsigned char_FAR* curp; unsigned istemp; short token; }FILE; But for using FILE in our program, we need not go through the members of the FILE structure. We can just use FILE pointer to create and use FILE for different operations. Prototype
  • 3. FILE* filePointerName; Example: Code: FILE *fp; FILE *inFile; FILE *outFIle fopen() Prototype fopen(“fileName”,”mode”); Example: Code: FILE *fp = fopen("test.txt","w"); FILE *inFile = fopen("test.txt","r"); fclose() Prototype fclose(filePointer); Example: Code:
  • 4. FILE *fp = fopen("test.txt","w"); fclose(fp); File Access Mode While opening a file, we have to specify the mode for opening the file. Here is a list of different modes for opening any file and usage of these mode. r - Read mode - Read from a specified file which already exists. If the file doesn’t exist or is not found, this operaiton fails. r+ - Read mode(+ some others) - Read from and write into an existing file. The file must exist before the operation. w - Write mode - Create new file with specified name. If the file exists, contents of the file is destroyed. w+ - Write mode(+ some others) - Write into an file. It also permits to read the data. a - Append mode - It appends content to the specified file. If the file doesn’t exist, it is created first, and then contents are written into it. a+ - Append mode(+some others) - Open a file for reading and appending. Example: Here is an example of opening a file in write mode. First, a file pointer fp is declared. Then fp is used to open a file named
  • 5. “test.txt” in ‘w’ mode, which stands for write mode.If fp is null, it means that file could not be opened due to any error. Code: int main() { FILE *fp; fp = fopen("test.txt","w"); if(fp==NULL) { printf("Error in openinng file"); } else printf("File has been created successfully"); } In file handling, we will use some data types besides the common data types. Here goes some discussion on these data types: size_t - It represents the size of any object in byte. For example, the sizeof() function returns the size of any object in size_t type which is unsigned integral type. fpos_t - It is used to specify a position within a file. In different portions of the program, we may need to get and set the position of file pointer, Generally, any fpos_t object is filled by callingfgetpos() function and the position is read by fsetpos() function.
  • 6. Now we will understand in brief the major functions needed for file handling in C. fputs() fputs is used to write data in file. Prototype of this function is: int fputs(const char* str, FILE* stream ); Parameters str: constant character pointer or string that is to be written in the file. stream: pointer to the file in which the data is to be written. Return Type: integer Value: On success Non negative value and On failure: End of file(EOF), setting the error indicator fgets() fgets is used to read data from file. Prototype of this function is: char* fgets(char* str,int count,FILE* stream); Parameters
  • 7. str: character pointer that will point to the returned data from file. count: integer that is the maximum count of character to return from the file.If the number is n, then (n-1) character is returned from the file. If the number of characters is less than n-1, then full data from the file will be returned. stream: pointer to the file from which the data will be fetch. Return: Type: character pointer(char*) Value: On success String which is read On failure Null pointer, setting the error indicator Example fputs and fgets Code: int main() { FILE* fp; char ch[20]; fp = fopen("testFile.txt","w"); if(fp == NULL) printf("Error in creating file"); else fputs("This is a test file",fp); fclose(fp);
  • 8. fp = fopen("testFile.txt","r"); if(fp == NULL) { printf("Error in opening file"); } else { fgets(ch,20,fp); printf("n%s",ch); } getch(); return 0; } In this example, a file is opened in write mode. After successful opening, a string is put in the file using fputs() function. The file is then closed and again opened in read mode. Next using fgets() function, twenty characters are read from starting position of the file and printed it on the console. fputc() It is used to write one by one character in file. Function prototype is: int fputc ( int character, FILE * stream ); Parameters
  • 9. character: The character to be written in the file. stream: pointer to the file in which data will be written. Return Type: integer Value: On success Integer value of the character which is written On Failure EOF is returned, setting the error indicator. A character is written in the position specified by the file pointer. After the write operation of every character, file pointer increases by one and moves to the next position. Example Code: int main() { FILE * fp; int len, count; char buffer[20] = "Good morning"; len = strlen(buffer); fp = fopen ("file.txt","w"); if (fp == NULL) printf ("Error in opening file"); else { for(count = 0; count < len; count++) fputc(buffer[count],fp); fclose (fp); }
  • 10. return 0; } In this function, a string is defined at the beginning. After opening a file in write mode, if successfully opened, copy the string by one character after another. Here, fputc() is used to write the character in the file. fgetc() It is used to read one by one character from file. Function prototype is: int fgetc ( FILE * stream ); Parameters stream: Pointer to the file from which data will be read. Return Type: integer Value: On Success integer value of the character which is read On Failure Null pointer, setting the error indicator It returns the character which is currently pointed by the FILE pointer. Example Code:
  • 11. int main() { FILE * fp; int count = 0; char ch; fp = fopen ("file.txt","r"); if (fp == NULL) printf ("Error in opening file"); else { while((ch = fgetc(fp)) != EOF) count++; printf("There are %d words in the file",count); fclose (fp); } return 0; } Here, a file is opened in read mode. Then until the end of file, characters are read from the file(with punctuation and space)using fgetc()and count of characters are increased. When it reaches EOF, total number of character is printed on the screen. fprintf() fprintf() works like printf(), with some differences. While printf() works for standard ouput, fprintf() is for file writing. The protype is: int fprintf(FILE * stream, const char* str);
  • 12. Parameters stream: pointer to the file in which the data is to be written. str: character pointer to the data to be wriitten, which can include the format of the data. Return Type: integer Value: On success number of characters which is written On Failure Negative number. Example Code: int main() { char* book[] = {"Shonchoyita","Shonchita","Oporajito","Bonolota"}; char* author[] = {"Rabindranath","Nazrul","Bivutibhushan","Jibonanondo"}; FILE* fp; int count; fp = fopen("BookList.txt","w"); if(fp == NULL) { printf("Error in opening file"); } else { for(count = 0; count < 4; count++)
  • 13. { fprintf(fp,"%-10s %-10sn",book[count],author[count]); } } fclose(fp); } In this example, arrays of book and author are defined. A text file named BookList.txt is opened in write mode. Then the data of book and author is written into this file using a file pointer and fprintf() function. fscanf() fscanf() works like scanf() function, with some differences. While scanf() works for standard input, fscanf() is for file reading. The prototype is: int fscanf(FILE * stream, const char* str); Parameters stream: pointer to the file from which the data is to be read. str: character pointer to the data to be read. It is mainly the format of the data. Return Type: integer Value: On success number of arguments which is filled
  • 14. On failure error indicator is set and EOF is returned. Example Now, we will perform the file read operation using fscanf() function from the BookList.txt file we have created previously. Code: int main() { FILE* fp; char bookName[50],bookAuthor[50]; fp = fopen("BookList.txt","r"); if(fp == NULL) { printf("Error in opening file"); } else { while(fscanf(fp,"%s %s",bookName,bookAuthor)!= EOF) { printf("%-10s t%-10sn",bookName,bookAuthor); } } } In this example, existing text file BookList.txt is opened in read mode. Then, using the file pointer, the book name and author name is read from the file using fscanf() funciton and pointed by two characters stored in two character array named bookName and bookArray until the end of file is found. After every read
  • 15. operation, the result is shown in the console using printf() function. fwrite() It is used for file writing. Prototype is: size_t fread(const void* ptr,size_t size,size_t count,FILE* stream) Parameters: ptr: pointer to the data which will be stored. size: the size of data elements (in byte) to be written. count: number of data elements to be written. stream: the pointer to the file where the data will be written. Return Type: size_t Value: On success number of elements which are successfully written On failure zero (0) if the size or count is 0. Error indicator is set. Example Code: int main() { struct book { char title[20];
  • 16. char author[20]; }; struct book bengaliBook[4] = { "Shonchita","Rabindranath", "Shonchoyita","Nazrul", "Oporajito","Bivutibhushan", "Bonolota","Jibonananda" }; FILE* fp; int count; fp = fopen("BookList.txt","w"); if(fp == NULL) { printf("Error in opening file"); } else { for(count = 0; count < 4; count++) { fwrite(&bengaliBook[count],sizeof(bengaliBook[count]),1,fp); } } fclose(fp); return 0; } In this example, a book structure with two member-title and author is declared. A structure array bengaliBook is declared and initialized. Then a file named BookList.txt is opened in write mode. Then, the four elements of the structure array is written
  • 17. in the file, each of which(elements) contains a book title and author name. fread() It is used to read data from file. Prototype of the function is: size_t fread (void* ptr,size_t size,size_t count,FILE* stream) Parameters ptr: pointer to memory where the read data will be stored. size: size of data elements (in byte) to be read. count: number of data elements to be read. stream: pointer to the file from which the data will be read. Return Type: size_t Value: On success number of elements which are successfully read. On failure returns zero (0) if the size or count is 0, Error indicator is set. Example Code: int main() { struct book {
  • 18. char title[20]; char author[20]; }banglaBook; FILE* fp; int count; fp = fopen("BookList.txt","r"); if(fp == NULL) { printf("Error in opening file"); } else { for(count = 0; count < 4; count++) { fread(&banglaBook, sizeof(banglaBook),1,fp); printf("%-10s %-10sn",banglaBook.title,banglaBook.author); } } fclose(fp); return 0; } In this example, the same book structure is used. A structure variable named banglaBook is declared. Then the text file BookList.txt is opened in read mode. We have written four elements of the book structure array named bengalibook in this text file in previous example. Now we will read those information. Using file pointer, every time we read data from the
  • 19. text file. The size of the read data in every iteration of the loop is equal to the size of the book structure variable banglaBook. Then the read data is displayed in the console. freopen() It is used to reopen a file. Prototype is: FILE *freopen(const char *filename, const char *mode, FILE *stream) Parameters filename: Name of the file which is to be re opened. mode: Access mode of the file . stream: Pointer to a FILE object that identifies the stream to be reopened. Return TYPE: File pointer. Value: On success pointer to the file which is reopened. On failure NULL pointer. The third parameter is the file stream associated with the specified file. The file is accessed with the specified access mode and associates with it the file stream. If this stream is already associated with some other file(s), then this function first closes the files, disassociates the stream, opens the specified file and associates it with the stream.
  • 20. Example Code: int main () { FILE *fp; fp = freopen("file.txt", "w", stdout); if(fp == NULL) printf("Error in reopening file"); else printf("hi world from consolen"); fclose(fp); return(0); } In this example, freopen() associates stdout with file.txt with write access mode. So, anything available on the stdout stream, is written into file.txt. After running the example, we will see that “hi world from console”, which is available in standard output, has been written in file.txt. fflush() It is used to flush buffer. Prototype is: int fflush ( FILE * stream ); Parameters
  • 21. stream: Pointer to a file that specifies a buffered stream. Return Type: integer Value: 0 On success. On failure a number indicating the error type Use case of fflush() is platform dependent. Generally it is used to clear the output buffer before any input operation. Example Code: char buffer[50]; int main() { FILE * fp; fp = fopen ("file.txt","r+"); if (fp == NULL) printf ("Error in opening file"); else { fputs ("Brazil",fp); fflush (fp); fgets (buffer,20,fp); fclose (fp); return 0; } } In this example, after between fputs() and fgets() operation, fflush() is used to clear the buffer. feof()
  • 22. It is used to check whether end of file for a stream is set or not. Prototype of the function is: int feof ( FILE * stream ); Parameters stream - Pointer to a file. Return Type: integer Value: Non zero value if EOF is set for the stream Zero Otherwise. By using file pointer as a parameter of feof(), we can check whether end of file has been reached or not. Example Code: int main () { FILE * fp; int n = 0; fp = fopen ("file.txt","r"); if (fp==NULL) printf ("Error opening file"); else { while (fgetc(fp) != EOF) { continue; }
  • 23. if (feof(fp)) { puts ("End of file"); } else puts ("Something wrong, error of file not found"); fclose (fp); } return 0; } In this example, we have read the content of the file by each character till the end of file and have checked whether the end of file is found or not. fseek() It is used to set file pointer to any position. Prototype is: int fseek ( FILE * stream, long int offset, int origin ); Parameters Stream: pointer to a file. Offset: Number of bytes or characters from the origin. Origin: The original position is set here. From this position, using the offset, the file pointer is set to a new position. Generally, three positions are used as origin: SEEK_SET - Beginning of file SEEK_CUR - Current position of the file pointer SEEK_END - End of file
  • 24. Return Type: Integer Value: On success Zero (0) On failure Non-Zero Example Code: int main () { FILE * fp; fp = fopen ( "file.txt" , "w" ); if (fp==NULL) printf ("Error in opening file"); else { fputs ( "I am supporter of France." , fp ); fseek ( fp , 18 , SEEK_SET ); fputs ( "Brazil" , fp ); fseek( fp , 0 , SEEK_CUR ); fputs ( " and Portugal" , fp ); fclose ( fp ); } return 0; } Then using SEEK_SET and offset, the word France is replaced by Brazil. Then by using SEEK_CUR, and position is appended with the string. ftell()
  • 25. It is used to get current position of the file pointer. The function prototype is: long int ftell ( FILE * stream ); Parameters stream: Pointer to a file. Return Type: long integer. Value: On success value of current position or offset bytes On failure -1. System specific error no is set Example Code: int main () { FILE * fp; long int len; fp = fopen ("file.txt","r"); if (fp==NULL) printf ("Error in opening file"); else { fseek (fp, 0, SEEK_END); len=ftell (fp); fclose (fp); printf ("The file contains %ld characters.n",len); } return 0;
  • 26. } In this example, file.txt is opened and using fseek(), file pointer is set to the end of the file. Then, ftell() is used to get the current position, i.e. offset from the beginning of the file. fgetpos() It is used to get current position of the file stream. Prototype of the function is: int fgetpos ( FILE * stream, fpos_t * pos ); This function gets the current position of the file pointer and stores it in fpos_t object. Then we can set the file pointer to this position in any time and perform required operation. Prameters stream: Pointer to a file stream. pos: Pointer to an object that stores the position value. Return Type: integer Value: On success zero(0) On failure system specific error no. fsetpos()
  • 27. It is used to set current position of the file pointer. Function prototype: int fsetpos ( FILE * stream, const fpos_t * pos ); In the fpos_t pointer pos, a position is specified. The file pointer is then set to this position. Parameters stream: Pointer to a file. pos: Pointer to a fpos_t object. The position to which the file pointer is to be set is previously stored here. Return Type: integer Value: On success zero(0). On failure system specific error no. Example fgetpos fsetpos Code: int main () { FILE * fp; fpos_t pos; fp = fopen ("file.txt","w"); if (fp==NULL) printf ("Error in opening file"); else { fgetpos (fp, &pos);
  • 28. fputs ("France is my favourite team",fp); fsetpos (fp, &pos); fputs ("Brazil",fp); fclose (fp); } return 0; } The above example clarifies both fgetpos() and fsetpos() function. After opening file, fgetpos() is used to get the initial position of the file pointed by file pointer fp and store it into fpos_t pointer pos. Then some text is written into the file, so file pointer is now changed. If we want to set the file pointer to the starting of the file, we can use fsetpos() function. This function sets the current position of the file pointer to the position pointed by fpos_t pointer pos, which is now the initial position of the file. rewind() It is used to set the file pointer at the beginning of the file. Function prototype: void rewind ( FILE * stream ); Parameters stream: Pointer to a file. In any stage of the program, if we need to go back to the
  • 29. starting point of the file, we can use rewind() and send the file pointer as the parameter. Example Code: int main () { int n; FILE * fp; fp = fopen ("file.txt","w+"); if (fp==NULL) printf ("Error in opening file"); else { fputs ("France is my favorite team",fp); rewind (fp); fputs("Brazil",fp); fclose (fp); } return 0; } In the above example, first, some string is written in the file. Then rewind() is used to set the file pointer at the beginning of the file. Then overwrite a word. perror() It is used to print error message. Function prototype: void perror ( const char * str );
  • 30. Parameters str: String that contains the custom error message is provided by the developer. It may be null pointer, if no custom message is intended to provide. Conventionally, application name is used as the parameter. Handling error message? Whenever an error occurs, an error no is generated (header file – errno.h). This error no is associated with specific error message. So, whenever we get an error, we can print the error using perror() to see exactly what happened. But remember, the system error message is platform dependent. If we want to give a custom error message along with the system error message, we have to sent the error message as a parameter to perror() function like- perror(“custom error message.”). The error message will be printed in stderr(standard error output stream). The format of printed error message is: Code: Custom error message: System error message. If no custom error message is sent, then only the system error message is printed: System error message.
  • 31. Whenever there is a possibility of occurring any error, we should use perrror() function. Example Code: int main () { FILE * pFile; pFile=fopen ("unexist.ent","rb"); if (pFile==NULL) perror ("The following error occurred"); else fclose (pFile); return 0; } Output: Code: ERROR: No such file or directory Example 2: with no parameter in perror(). Code: int main () { FILE * fp; fp = fopen ("fileTest.txt","r"); if (fp==NULL) perror (""); else fclose (fp); return 0;
  • 32. } Output: Code: No such file or directory Binary files We can handle any binary file and perform the above fucntionalities in those files. The main difference between binary file and text file handling is access mode. We have to add a character ‘b’ with each of access mode while working with binary file. For example, ‘rb’ is used for read mode while ‘wb’ is used for write mode for binary file accessing. From the above discussion, we have learnt some useful lessons for file handling in C. Hopefully it will help us to perform basic file I/O operations. Understanding File Descriptor and File Pointer Contributed by Trinity On 25th August, 2012 This is an article on Understanding File Descriptor and File Pointer in C.
  • 33. During C programming, file operations are pretty common. And when you are writing programs in C on Linux, two familiar terms related to file operations are File Pointers and File Descriptors. We know both are different, but what are they? This article will focus on understanding what are file descriptors, file pointers and how are they related at the kernel level. Understanding individually File Descriptor is an integer value at the kernel level which identifies the file to be operated during the program. Here, its worth mentioning, that everything on Linux is a file. In C system programming, we have following method to open a file: Code: int fd = open ("/etc/myfile.txt", O_WRONLY); This system call returns the file descriptor. However, Standard C also provides another method for opening a file, Code: FILE *fp = fopen ("/etc/myfile.txt", "w"); This C library method returns a file pointer. File Pointer is a pointer to a C structure, identifying a file,
  • 34. wrapping the file descriptor, buffering functionality and all other functionality needed for I/O operation. The file pointer is of type FILE, whose definition can be found in "/usr/include/stdio.h". This definition may vary from one compiler to another. Here is one such definition: Code: typedef struct { unsigned char *_ptr; int _cnt; unsigned char *_base; unsigned char *_bufendp; short _flag; short _file; int __stdioid; char *__newbase; #ifdef _THREAD_SAFE void *_lock; #else long _unused[1]; #endif #ifdef __64BIT__ long _unused1[4]; #endif /* __64BIT__ */ } FILE; Hence, talking about differences between a file pointer and a file descriptor,
  • 35.  File Pointer includes various I/O functionality like buffering, EOF detection, etc whereas File Descriptor does not.  File Pointer is the most widely used and standardized, however, File Descriptor is a low level kernel variable and limited to Linux. Deeper Understanding - At the Kernel level The Kernel maintains a Kernel File Table for every open file by any process. Each entry in this kernel file table is identified by our File Descriptor. Hence, any file opened by any process would have a file descriptor and that file would have its entry maintained in the kernel file table until it is closed. Another interesting fact is, even if the same file on the disk is opened by two different processes, they would have their own separate file table entries in the kernel file table with separate file descriptor values. This is needed to store the mode of open, current file position, etc for each opened instance of the file. Generally, an entry in the kernel file table would consist of:  File Descriptor  Current File Position  inode info  vnode info  file metadata  etc However, every process also has its own File Descriptor (FD) table, which is basically a data structure identifying the opened file instance and includes a pointer to the entry in the kernel file
  • 36. table. Each entry in this FD table is of the opened file in the process. At the userspace level, the file pointer is used to read/write onto a file. Whereas, at the system level, it uses the lower level variable file descriptor. Here is an abstract illustration: So, when we write the code Code: 1. File *fp; 2. fp = fopen ("/etc/myfile.txt", "w"); 3. fclose(fp); In statement 1, a 4 byte memory for the pointer is created of type 'FILE' on stack. In statement 2, a memory = 'sizeof(FILE)' is allocated on heap, and address of which is assigned to the pointer 'fp'. Along with, a new entry created in the FD table of the process followed by, an entry created in the kernel file table
  • 37. representing the newly opened file instance having a unique FD. During the read/write/other IO operations, values are maintained by the Kernel File Table entry. In statement 3, all the allocated memory for file pointer is released and the entry is deleted. File Pointer from File Descriptor Use method Code: FILE * fdopen (int fd, const char *mode); The header file is "stdio.h" Example: Code: #include <stdio.h> #include <fcntl.h> int main() { int fd; FILE *fp; fd = open ("myfile.txt", O_WRONLY | O_APPEND| O_CREAT); if (fd < 0) {
  • 38. printf("Error opening file through FDn"); exit (1); } write (fd, "Writing using FDn", 17); fp = fdopen(fd, "a"); fprintf(fp, "Writing using File Ptrn"); fclose (fp); close(fd); return 0; } Here is the Output: Code: [fedora@fedora16 fdfptr]$ sudo cat myfile.txt Writing using FD Writing using File Ptr File Descriptor from File Pointer Code: int fileno(FILE * fp); The header file is again "stdio.h". Example: Code: #include <stdio.h>
  • 39. #include <fcntl.h> int main() { int fd; FILE *fp; fp = fopen ("myfile.txt", "a+"); if (fp == NULL) { printf("Error opening file through FPn"); exit (1); } fprintf(fp, "Writing using File Ptrn"); fd = fileno (fp); write (fd, "Writing using FDn", 17); fclose (fp); close(fd); return 0; } Here is the Output: Code: [fedora@fedora16 fdfptr]$ sudo cat myfile.txt Writing using FD Writing using File Ptr Conclusion
  • 40. Now we know what internally file descriptor and file pointer is, and how they work in their respective spaces. Also, we know how to get one from the other. So, keep playing and exploring and share any interesting fact you get across. Opening A File Before we can write information to a file on a disk or read it, we must open the file. Opening a file establishes a link between the program and the operating system, about, which file we are going to access and how. We provide the operating system with the name of the file and whether we plan to read or write to it. The link between our program and the operating system is a structure called FILE which has been defined in the header file “stdio.h” . Therefore, it is necessary to always include this file when we are doing high level disk I/O. When we request the operating system to a file, what we get back is a pointer to the structure FILE. That is why, we make the following declaration before opening the file, FILE*fp ; Each file we open will have its own FILE structure. The FILE structure contains information about the file being used, such as its current size, its location in memory etc. More importantly it contains a character pointer which points to the character that is about to get read. Now let us understand the following statements, FILE *fp ; fp = fopen ( “PR1.C”, “r” ) ; fp is a pointer variable, which contains address of the structure
  • 41. FILE which has been in the header file “stdio.h”. fopen( ) will open a file “PR1.C” in ‘read’ mode, which tells the compiler that we would be reading the contents of the file. Note that “r” is a string and not a character; hence the double quotes and not single quotes. In fact, fopen( ) performs three important tasks when you open the file in “r” mode: (a) Firstly it searches on the disk the file to be opened. (b) If the file is present, it loads the file from the disk into memory. Of course if the file is very big, then it loads the file part by part.If the file is absent, fopen( ) returns a NULL.NULL is a macro defined in “stdio.h” which indicates that you failed to open the file. (c) It sets up a character pointer which points to the first character of the chunk of memory where the file has been loaded. Reading from A file Once the file has been opened for reading using fopen( ), the file’s contents are brought into memory and a pointer points to the very first character. To read the file’s contents from memory there exists a function called fgetc( ). This has been used in our sample program through, ch = fgetc ( fp ) ; fgetc( ) reads the character from current pointer position, advances the pointer position so that it now points to the next character, and returns the character that is read, which we collected in the variable ch. Note that once the file has been opened, we refer to the file through the file pointer fp.
  • 42. We have to use the function fgetc( ) within an indefinite while loop. There has to be a way to break out of this while,it is the moment we reach the end of file. End of file is signified by a special character in the file, when it is created. This character can also be generated from the keyboard by typing ctrl Z. While reading from the file, when fgetc( ) encounters this special character, instead of returning the character that it has read, it returns the macro EOF. The EOF macro has been defined I the file “stdio.h”. In place of the function fgetc( ) we could have as well used the macro getc( ) with the same effect. Opening A File There is a possibility that when we try to open a file using the function fopen( ), the file may not be opened. While opening the file in “r” mode, this may happen because the file being opened may not be present on the disk at all. And you obviously cannot read a file which doesn’t exist. Similarly, while opening the file for writing, fopen( ) may fail due to a number of reasons, like, disk space may be insufficient to open a new file, or the disk may be write protected and so on. So it is important for any program that accesses disk files to check whether a file has been opened successfully before trying to read or write to the file. If the file opening fails due to any of the several reasons mentioned above, the fopen( ) function returns a value NULL (defined in “stdio.h” as #define NULL 0). Here is how this can be handled in a program… Code: C
  • 43. #include “stdio.h” main() { FILE*fp ; Fp = fopen ( “PR1.C”,”r” ) ; if( fp == NULL ) { puts ( “cannot open file” ) ; exit() ; } } File Opening Modes We open the file in read ( “r” ) mode. However, “r” is but one of the several modes in which we can open a file. Following is a list of all possible modes in which a file can be opened . the tasks performed by fopen( ) when a file is opened in each of these modes are also mentioned. r :- Searches file. If the file exists, loads it into memory and sets up a pointer which points to the first character in it. If the file doesn’t exit it returns NULL. Operations possible – reading from the file. w :- Searches file. If the file exists, its contents are overwritten. If the file doesn’t exit, a new file is created. Returns NULL, if unable to open file. Operations possible – writing to the file.
  • 44. a :- Searches file. If the file exists, loads it into memory and sets up a pointer which points to the first character in it. If the file doesn’t exist, a new file is created. Returns NULL, if unable to open file. Operations possible – appending new contents at the end of file. r+ :- Searches file. If it exists, loads it into memory and sets up a pointer which points to the first character in it. If file doesn’t exist it returns NULL. Operations possible – reading existing contents, writing new contents, modifying existing contents of the file. w+ :- Searches file. If the file exists, its contents are destroyed. If the file doesn’t exist a new file is created. Returns NULL, if unable to open file. Operations possible – writing new contents, reading them back and modifying existing contents of the file. a+ :-Searches file. If the file exists, loads it in to memory and sets up a pointer which points to the first character in it. If the file doesn’t exist, a new file is created. Returns NULL, if unable to open file. Operations possible – reading existing contents, appending new contents to end of file. Cannot modify existing contents. Writing to A File The fputc( ) function is similar to the putch( ) function, in the sense that both output characters. However, putch( ) function always writes to the VDU, whereas, fputc( ) writes to the file. Which file? The file signified by ft. the writing process continues
  • 45. till all characters from the source file have been written to the target file, following which the while loop terminates. We have already seenthe function fgetc( ) which reads characters from a file. Its Counterpart is a function called fputc( ) which writes characters to a file. As a practical use of these character I/O functions we can copy the contents of one file into another, as demonstrated in the following example. This program takes the contents of a text file and copies them into another text file, character by character. Example Code: C #include “stdio.h” main() { FILE *fs, *ft ; char ch ; fs = fopen ( “pr1.c”, “r” ) ; if ( fs == NULL ) { puts ( “Cannot open source file” ) ; exit( ) ; } ft = fopen ( “pr2.c”, “w” ) ; if ( ft == NULL ) { puts ( “Cannot open target file” ) ;
  • 46. fclose ( fs ) ; exit( ) ; } while ( 1 ) { ch = fgetc ( fs ) ; if ( ch == EOF ) break ; else fputc ( ch, ft ) ; } fclose ( fs ) ; fclose (t } Closing The File When we have finished reading from the file, we need to close it. This is done using the function fclose( ) through the statement, fclose ( fp ) ; this deactivates the file and hence it can no longer be accessed using getc( ). Once again we don’t use the
  • 47. filename but the file pointer fp. Loops in C - for while do while and goto Contributed by faribasiddiq () On 22nd December, 2013 This is an article on Loops in C - for while do while and goto in C. Loops are the basic logic building structures in computer programming. It is a way of executing statement(s) repeatedly in specified times, which is termed as iteration. Here different types of loops in C language will be discussed. All of them have same goal, but their way of working is different. The topics of discussion of this article would be to understand the following loops in C programming:  for Loop  while Loop  do while Loop  goto for Loop It is very easiest to understand out of all loops. Generally it is used when number of iteration is known to a programmer. Traditionally, a basic for loop has four parts:  Initialization  Condition  Update(Increment/Decrement)  Statements
  • 48. Here is the basic syntax of for loop. Code: for (variable(s) initialization; condition(s); update value of variable(s)) { statement 1; . . . . . . . . . . . . statement N; } For a beginner, it must not be that easy to understand the syntax. For elucidation, an example is given: Code: int main() { int i; for(i = 0; i < 5; i++) printf("%d", i); } Illustration for different parts of the loops for above example is as follows:  i = 0 initialize the loop control variable i.  i < 5 is condition for the loop. The loop continues till the value of i is less than 5.  i++ increments the value of i by 1. It means i+1.  printf("%d", i) is the statement of the loop. Value of i is displayed in the console by this statement.
  • 49. The steps involved in working of the above example are: Step 1: i = 0. So condition (i < 5) is true. Update the value of i by 1. But the updated value will work for next iteration. Print the value of i. The value that will be printed will be 0. Step 2: Now i = 1. So Condition is true. Update the value of i by 1. But the updated value will work for next iteration. Print the value of i. The value that will be printed will be 1. Step 3, 4, 5: Working procedure is as the previous one and print the value 2,3,4 accordingly. Step 6: Now i = 5. So Condition is false. So, exit the loop. So the building blocks of for loop are:  Initialize the loop variable(s).  Check the condition for next iteration.  Update the value of loop variable.  Statement(s). The value of loop control variable can be updated by any amount. For example, i+=2 can be used for incrementing the value by 2. Some other operators can be used for updating the value of loop control variable such as decrement (-), multiplication (*), divide (-) etc. besides increment operator (+). The benefit of using for loop is immense. An example may help in explanation. Suppose you will be given two numbers x and y. You have to find out the summation of all numbers from x to y
  • 50. including these numbers. How can this be done? For loop makes it quite easy for you. Code: int main() { int x,y,num,sum = 0; scanf("%d %d",&x,&y); for(num = x; num <= y; num++) sum = sum + num; printf("Summation of %d to %d is %d",x, y, sum); } You can use multiple variables for loop control. Initialization, condition and update, every block can work with multiple variables.  In initialization and update, separate the two variable using coma(,) separation.  In condition, use logical and, or (&&, ||) according to your need. Why should multiple variables be used? Suppose two sprinters x and y are there and speed of y is double of speed of x. They are going to participate in a 30 meter sprint. x has started from 10 meters ahead of y. Who have won the race? In different stages of race, what is their position? Their positions can be obtained in the following manner: Code: int main() { int x,y; for (x=10, y=0 ; x <= 30 && y <= 30 ; x++, y= y+2)
  • 51. { printf("%dt%dn",x,y); } return 0; } Nested for loop: You can use one for loop inside another. It is called nested for loop. Basic syntax for nested for loop is: Code: for (initialization; condition; update) { for (initialization; condition; update) { statement(s); } } The process to draw a triangle using nested for loop is given: Code: int main() { int i,j,rows; printf("Enter the number of rows"); scanf("%d",&rows); for(i=1;i<=rows;++i) { for(j=1;j<=i;++j) { printf("*");
  • 52. } printf("n"); } return 0; } The number of rows have been assumed as 3. Then for every row, inner loop executes i times. the simulation is given here: Input 1 : i = 1, j = 1 Output: * Input 2 : i = 2, j = 1, 2 Output: * * Input 3 : i = 3, j = 1, 2, 3 Output: * * * One of the uses of nested loops is for creating two dimensional array or matrix. Initialization of any matrix is done using nested for loop. Suppose you will make a row*col matrix. An example is given below showing how to initialize and access it. Code: int mat[10][10]; int i,j,row,col; printf("Enter order of matrix="); scanf("%d%d",&row,&col); printf("Enter Elements: "); for(i=0;i<row;i++) { for(j=0;j<col;j++)
  • 53. { scanf("%d",&mat[i][j]); } } for(i=0;i<row;i++) { for(j=0;j<col;j++) { printf("row[%d] col[%d]= %dn",i,j,mat[i][j]); } } while Loop While loop can be thought as repetition of if statement.It is also known as pre- test loop as condition check is done before execution of the block. Here is the basic syntax of a while loop: Code: While(condition) { statement(s); } Everything that can be done using for loop can be done using while loop also. Remember the program that printed 0 to 4 using for loop. Below a while loop implementation is given. It will give basic understanding about while loop.
  • 54. Code: int main() { int i = 0; while(i < 5) { printf("%d",i); i++; } } Here, initialization is before for loop. Updating loop control variable is done inside loop. While loop provides some advantages when number of iteration is not known. Suppose, you will take input continuously from keyboard until a negative value is given. Here, number of iteration of the loop is unknown to you. How while loop handles it is depicted here. Code: int main() { int num = 0; while(num >= 0) { printf("Enter new number"); scanf("%d",&num); }
  • 55. } You can use multiple conditions in while loop. Let us play a guessing game. I will randomly pick a number from 1 to 20. You will try to guess it. I will give you hints every time whether you got it, or you should try smaller number, or greater number. I will give you 5 chances. This can be done using while loop in the following manner. Code: int main { int secretNum, guessNum = 0; int usedChance = 0; int maxChances = 5; srand((unsigned int)time(NULL)); secretNum = rand() % 20 + 1; printf("Guess a number from 1 to 20.You will get %d chancesn",maxChances); while(guessNum != secretNum && usedChance < maxChances ) { scanf("%d",&guessNum); if(guessNum == secretNum) printf("Congrats.You have got it.n"); else if(guessNum < secretNum) printf("Try a bigger number.n"); else printf("Try a smaller number.n"); usedChance++; }
  • 56. return 0; } You might change it slightly. Do not limit the chance to 5 times. Give unlimited chances until the right number is guessed. Look how many chance one player needs to get the number. Do it yourself. Like nested for loop, while loop also has nested version. Basic syntax is: Code: while (condition1) { while (condition2) { statement(s); } } Remember the for loop section. There was a matrix operation using nested for loop. Matrix can also be initialized using nested while loop. Code: i =0; while(i < row) { j = 0; while(j < col) {
  • 57. scanf("%dt",&mat[i][j]); j++; } i++; } Similarly the value of matrix can be accessed. do while Loop do-while loop is a variation of while loop. The condition is checked by a while loop and statements are in do segment. It is also known as post-test tool as it first executes the block and then checks the condition. Here is the basic syntax : Code: do{ statement(s); }while(condition); Look at some comparison between while and do while.  While loop first checks the condition, if the condition is satisfied, then the statements are executed. In other hand, do-while loop first executes statements one time and then check the conditions for the next iteration.  In while loop, it is possible that statements inside loop will not be executed entirely, if condition fails for the very first time. On
  • 58. the other hand, statements in do-while loop will be executed at least one time. The iteration of a do while loop is as below. Code: int max = 5; int i = 0; do{ i++; printf("%dn",i); }while(i < max); The program prints the value from 1 to 5. In do segment, it increments the loop control variable and print the value. In while section, it checks if the value of loop control variable is less than another variable. Remember any game or application which shows you the menu and allows you to select any option. Then according to your choice, does some operation. For example, some menu like this: Select any one from the menu: 1. Add numbers. 2. Subtract numbers 3. Multiply numbers. 4. Divide numbers. 5. Exit. You then make a choice from 1-5 and program works accordingly. Look, at the beginning of the program, menu has
  • 59. been displayed to you once. That means it is independent of your choice of operation. Here lies the usage of do section of do-while loop. Code: int option = -1; float num1, num2; do { printf("Enter two numbers"); scanf("%f %f",&num1,&num2); printf("Select 1-5 for any operationn"); printf("1.Additionn"); printf("2.Subtractionn"); printf("3.Multiplicationn"); printf("4.Divisionn"); printf("5.Exit Programn"); scanf("%d", &option); printf("n"); switch(option) { case 1: printf("Summation result is =%.2fn",num1+num2); break; case 2: printf("Subtraction result is =%.2fn",num1-num2); break; case 3: printf("Multiplication result is =%.2fn",num1*num2);
  • 60. break; case 4: printf("Division result is =%.2fn",num1/num2); break; case 5: printf("Terminating..."); break; default: printf("Invalid operator"); break; } }while(option != 5); Every time you enter two numbers, program shows you the menu. You can choose 1-4 to make the calculation and 5 to exit. If you choose any other option other than 1-5, it prompts you that you have choosen the invalid operator and redirects you to the main menu again. The program continues until the exit option, that means option 5 is pressed. goto goto statement performs unconditional jump from one statement to another statement.But the this jump can be done in the same function, you can not use goto statement to jump from one function to another function. Basic syntax for goto is as follows. Code:
  • 61. statement; . . . goto label; statement; label: statement; For more clarification, the example below shows depending on conditional statement, how different label is executed and some statements are ignored. Code: if(player1Runs > player2Runs) goto player1 else goto player2 . . . . . . player1: printf(“I am player1, I have won the match”); player2: printf(“I am player2, I have won the match”); Here, if player1Runs is greater than player2Runs, it jumps to player1 label, otherwise jumps to player2 label using goto
  • 62. statement. You can use goto statement for looping. Instead of using for, while, do while loop, you can do the same job using goto. An example is shown below: Code: int i = 0; firstLoop: printf("%d",i); i++; if(i<10) goto firstLoop; printf("nout of first loop"); It is suggested not to use goto statements. The goal you achieve by using goto statement, can be achieved more easily using some other conditional statements like if-else if-else etc. Shortcomings of goto statement:  Make a mess of sequence of code  Unintended infinite loop  Reduces readability So, we have had a journey through the different kinds of loop. For long and repetitive task, loop is still the best logic structure. According to the situation, you may have to choose one which works best in that situation. So, start your practice and do the best use of loops in your programs. Custom Data Types in C - struct, union and typedef
  • 63. Contributed by faribasiddiq () On 2nd January, 2014 This is an article on Custom Data Types in C - struct, union and typedef in C. There are many built in data types in C. But sometimes, the built in data types are not enough to perform the required tasks. In that case, some custom data type can be built to meet the necessary requirements. In this tutorial, the following custom data types are going to be discussed:  Structure  Union  Typedef Structure Structure is the most commonly used custom data type. When you need to work with different variables of different data types (i.e. char, int, float ) for a specific task, you have to use structure. Prototype: Code: struct tag { dataType member 1; ..... ..... dataType member n;
  • 64. }; Example: Suppose an office has to make a list of all employees’ information in the office and employee information consists of employee name, designation, department, age and salary. For performing the task, a structure named employee may be declared which consists of the required information. Code: struct employee { char name[50]; char designation[50]; char dept[50]; int age; float salary; }; Different section of structure: definition Every structure consists of three parts: 1. The keyword struct 2. Tag 3. Members of structure 1) struct keyword: If the example above is considered, structure starts with the keyword struct. By this keyword, compiler is informed that a custom data type of structue is going to be declared.
  • 65. 2) Tag: It is generally the name of new data type. If the previous structure is considered, the tag is employee. It informs that the following structure will be used for employee. 3) Members: Structure members are grouped in a curly braces after the tag part. All the members which are needed to build the new data type are listed here. In previous example, new custom data type employee consists of name, designation, department, age and salary. These members are grouped along with their data type after the tag part. Variable declaration: The prototype of declaring a structure variable is as follows: Code: struct tag var1; For the above example, you need to declare a variable like below: Code: struct employee john; Here, struct employee is data type; john is variable of this data type. If more than one variable is required to declare, the code would be this way:
  • 66. Code: struct employee john, josheph; You can declare structure variable while declaring the structure. Code: struct employee { char name[50]; char designation[50]; char dept[50]; int age; float salary; } john, joseph; Access and initialize member of a structure: Consider another structure named birthDate. You need to keep this structure in mind for the upcoming examples. Different operations are going to be discussed using this structure. Code: struct birthDate { int day; int month; int year; }; Here, day, month and year are members of the structure birthdate. But how can these members be accessed and
  • 67. initialized? The way to access the default data types would be like below: Code: struct birthDate { int day; int month; int year; }; int main() { day = 1; month = 1; year = 1980; printf("%d-%d-%d",day,month,year); } The program returns following error: Code: Error 1 error C2065: 'day' : undeclared identifier Error 2 error C2065: 'month' : undeclared identifier Error 3 error C2065: 'year' : undeclared identifier Error 4 error C2065: 'day' : undeclared identifier Error 5 error C2065: 'month' : undeclared identifier Error 6 error C2065: 'year' : undeclared identifier
  • 68. So the structure members cannot be accessed like built in data types. The solution is to declare a structure member at first, then to use dot(.) operator to access each member. Code: int main() { struct birthDate johnBirthDate; johnBirthDate.day = 1; johnBirthDate.month = 1; johnBirthDate.year = 1980; printf("%d-%d- %d",johnBirthDate.day,johnBirthDate.month,johnBirthDate.year); } Here, structure birthDate member johnBirthDate is declared. Then, structure member is accessed using dot operator with this variable. More ways to initialize structure variable: Code: struct birthDate { int day; int month; int year; }johnBirthDate = {1,1,1980}; Code:
  • 69. struct birthDate { int day; int month; int year; }; struct birthDate johnBirthDate = {1,1,1980}; Data passing among structure members: One member’s value of a structure to another member can be copied or assigned. The example given below will clarify the scenario: Code: int main() { struct birthDate johnBirthDate; johnBirthDate.day = 5; johnBirthDate.month = johnBirthDate.day; johnBirthDate.year = 1980; printf("%d-%d- %d",johnBirthDate.day,johnBirthDate.month,johnBirthDate.year); } Here the statement: johnBirthDate.month = johnBirthDate.day copies data of structure member day to structure member month. Array vs Structure:
  • 70. Arrays in C work with group of variable. For example, Code: int employee[10]; Here, employee is an array of ten integer variables. But the thing is, only integer value in these ten variables can be stored. But one integer value is not enough to store employee information as it is necessary to store employee name, designation, department, age and salary for each employee.So we need a group of these variables. Code: char name[50]; char designation[50]; char dept[50]; int age; float salary; The concept of structure comes into action. Unlike array which groups similar data types, a structure is for different data types. Array of structure Till now, it has been discussed how to declare a variable of any structure and initialize the structure members using structure variable. What would you do if you need array of structure? For example, consider a situation where a database of all students
  • 71. of a class needs to be created. In this case, an array of a structure of student would be helpful. Code: struct student { char* name; int id; }; If you need to declare a variable of the structure , the way is: Code: struct student john; If you need to declare an array of this structure , the way is: Code: struct student CSE[100]; Initialization Structure Array Code: struct student CSE[3] = { "John",101, "Joseph", 108, "Maria",209 }; struct student CSE[3]= { {"John",101}, {"Joseph", 108}, {"Maria",209}
  • 72. }; Access structure array elements: An initialized array of structure has been declared. The demonstration below shows how to access the members. Code: int main() { int loopCount; printf("Database of CSE studentsn"); printf("NametIdn"); printf("---------------n"); for(loopCount = 0; loopCount < 3; loopCount++) { printf("%st%dn",CSE[loopCount].name, CSE[loopCount].id); } } The way to access the member of the structure goes this way: CSE[loopCount].name and CSE[loopCount].id. Therefore, the way to access is : Code: Structure tag[arrayIndex].structure_member Pointer to Structure:
  • 73. A pointer to a structure can also be defined. The following structure gives demonstration: Code: struct birthDate { int day; int month; int year; }; struct birthDate *johnBirthDate; It means johnBirthDate is a pointer of birthDate structure. Initialization: The way to initialize a pointer of a structure is slightly different. At first, memory for the pointer needs to be allocated. The size of the allocated memory is equal to the size of structure. Code: johnBirthDate = malloc(sizeof *johnBirthDate); Access structure member using pointer: When a pointer to a structure is declared, the structure members are accessed using arrow(->) operator, instead of dot(.) operator. Here is an example of whole process. Code: struct birthDate {
  • 74. int day; int month; int year; }; int main() { struct birthDate *johnBirthDate; johnBirthDate = malloc(sizeof *johnBirthDate); johnBirthDate->day = 1; johnBirthDate->month = 1; johnBirthDate->year = 1980; printf("%d-%d-%d",johnBirthDate->day,johnBirthDate- >month,johnBirthDate->year); } Everything is exactly same as the way structure variable works. The differences are – memory allocation, and use of arrow(->) operator instead of dot(.). Nested Structure: A structure can be declared as a member of another structure. The following structure clarifies the issue: Code: struct employee { int empId;
  • 75. char gender; float salary; }; It is assumed that the salary is not fixed for every employee. It depends on the working hours and salary per hour. So another structure for salary has to be declared. Code: struct salary{ int workingHour; float salaryPerHOur; }; Therefore, employee structure contains another structure named salary. Code: struct employee{ int empId; char gender; struct salary{ int workingHour; float salaryPerHOur; }employeeSalary; }myEmployee; Here, employeeSalary is a variable of salary structure and myEmployee is a variable of employee structure.
  • 76. How will be the members of a inner structure accessed? The way is: Code: OuterStructure.InnerStructure.InnerStructureMember; So, if it is needed to access workingHour and salaryPerHour of salary structure, then the way would be like this: Code: myEmployee.employeeSalary.workingHour; myEmployee.employeeSalary.salaryPerHour; Passing Structure as function Parameters: A structure variable can be sent to a function and structure can also be returned from function. Code: struct student { char* name; int id; }; void showStudentInfo(struct student st) { printf("Student Name: %sn",st.name); printf("Student Id: %dn",st.id); } int main()
  • 77. { struct student student1; student1.name = "John Richards"; student1.id = 109; showStudentInfo(student1); } In the above example, a variable of student structure student1 is created in main funciton. Then its members name and id are initialized. Next the structure variable student1 is sent to showStudentInfo function. The function recieves the variable with struct student datatype. Then the members of the structure cen be accessed from showStudentInfo structure. If the structure variable is passed to a function and the structure member value is changed, does it affect the caller function? Code: struct student { char* name; int id; }; void showStudentInfo(struct student st) { st.name = "J. Richards"; st.id = 110; printf("After changing valu in showStudentInfon"); printf("Student Name: %sn",st.name); printf("Student Id: %dn",st.id);
  • 78. } int main() { struct student student1; student1.name = "John Richards"; student1.id = 109; showStudentInfo(student1); printf("Back to main functionn"); printf("Student Name: %sn",student1.name); printf("Student Id: %dn",student1.id); } The ouput would be like this. Code: After changing valu in showStudentInfo Student Name: J. Richards Student Id: 110 Back to main function Student Name: John Richards Student Id: 109 So, if any structure variable is passed to any function, a local copy of that variable is made for that function. Any change of the variable in that function is limited to only that function. The scope of members of structure can be extended. The following example would elucidate: Code:
  • 79. struct student { char* name; int id; }; void showStudentInfo(struct student* st) { st->name = "J. Richards"; st->id = 110; printf("After changing valu in showStudentInfon"); printf("Student Name: %sn",st->name); printf("Student Id: %dn",st->id); } int main() { struct student student1; student1.name = "John Richards"; student1.id = 109; showStudentInfo(&student1); printf("Back to main functionn"); printf("Student Name: %sn",student1.name); printf("Student Id: %dn",student1.id); } Whats are the changes? The address of student1 variable has been passed to showStudentInfo function, it has been received with a structure pointer in that function and the value has been edited.
  • 80. The output generated will be: Code: After changing valu in showStudentInfo Student Name: J. Richards Student Id: 110 Back to main function Student Name: J. Richards Student Id: 110 Values have been changed in showStudentInfo function. After returning to the main funciton, the changed value of the members is got. Structure Memory Allocation: A structure is considered like this: Code: struct employee{ int empId; char gender; float salary; }emp1; How many bytes will be allocated for emp1? Size of a structure variable in memory is equal to the total size of all members of the structure. The structure employee consists of one char, one int and one float member. If the size of int, char and float are 2,1 and 4
  • 81. bytes individually, then total size of emp1 variable is = 2 + 1 + 4 = 7 bytes. Union Union is another commonly used custom data type beside struct. Besides, it provides some benefits on memory issue which structure does not provide. The details are discussed below: Prototype: Code: union tag { member 1; ... .... member n; }; Example: Suppose, you need to create a union of all employees’ information in an office . Code: union employee { char name[50]; char designation[50];
  • 82. char dept[50]; int age; float salary; }; Declaration of union is like structure except the keyword. The keyword is union for declaring a union while for structure, the keyword is struct. Variable declaration: It is also like structure variable declaration. Just the union keyword needs to be used instead of struct. Code: union employee myEmployee; It can also be done while declaring the structure. Code: union employee { char name[50]; char designation[50]; char dept[50]; int age; float salary; }myEmployee; Access and initialize member of a union
  • 83. This procedure is just same as the structure. Your concepts would clarifies if you go through structure carefully. Structure vs union The job which can be performed by union, can also be done by structure. So why should be union used? The reason lies in the memory consumption. The memory required for union is less than structure in most of the cases. The clarification is given with a structure and union with same members. Code: struct employee{ int empId; char gender; float salary; }myEmployee; union employee{ int empId; char gender; float salary; }myEmployee; Here, a structure and a union are declared both consisting of same members. Let us assume that memory consumption of int = 2 bytes, char = 1 byte, float = 4 byte. In structure, total memory consumption = 2 +1 +4 = 7 bytes. In union, total memory consumption is 4
  • 84. bytes. How is that possible? Union works in this concept: In some conditions, more than one variable is needed actually,but all the variables do not work at the same time. So the memory units needed to store the member that takes the maximum unit of memory can be taken and reused for other members. In the above example, out of three members of union, float data type takes most memory which is 4 bytes. Typedef It is a way of renaming built in data type(char, int) as well as custom data type(struct, union). So, for this union, 4 bytes memory is allocated and reused for other members when needed. Prototype: Code: typedef dataType newName; Example: Code: typedef char word; Here you would typedef the char data type to word. Now you can declare any char type data using word keyword instead of
  • 85. char. So, if you write: Code: word ch; It means the same with: Code: char ch; typedef for built in data type: You can typedef built in data types (i.e. int, float). For example: Code: typedef int Int16; typedef float F32; Then you can declare variable like this: Code: Int16 age, id; F32 salary; Typedef custom data type: It is possible to typedef the custom data type(structure, union, enumeraton)as well as built in data type. Typedef Structure: The birthDate structure is considered.
  • 86. Code: struct birthDate { int day; int month; int year; }; You can typedef it to another name(Date). Code: typedef struct birtDate Date; Then a variable using new name(Date) needs to be declared. Code: Date joiningDate; Typedef Union: To typedef union, the procedure is same as the structure. Code: union birthDate { int day; int month; int year; }; typedef union birtDate Date; Date joiningDate;
  • 87. Typedef Enumeration: Consider the following enumeration of color . Code: enum color{Red,Green,Blue}; You can typedef it to another name. Code: typedef enum color Color; Then the new name of the enum is to be udes to declare variable. Code: Color ball, leaf, sky; C Functions Contributed by msfq17a () On 30th December, 2013 This is an article on C Functions in C. Function is a block of statements that performs a specific task. It is reusable portion of the code and a very effective way to modularize your program. For example, you may need to perform different arithmetic operations in your program like addition, subtraction, multiplication and division. To implement it in a modular way, you can define four different functions to perform this individual
  • 88. task. There are two type of functions: 1. Library function 2. User defined function 1. Library function: Every language is accompanied by a collection of library function which is used to perform some common, frequently used operations. For example, we have seen the frequent use of printf() and scanf() function in our C programs. These two are library functions of C and are defined in header file stdio.h. Code: #include <stdio.h> int main() { printf("Hello world"); } 2. User defined function: Sometimes we need to modularize our program according to our requirement, which is not available in library. So, we need to define function ourselves, which is called user defined function. For example, you may want to greet user at the start of the program. This is how you can do this: Code: void greeting() { printf("Hello Friend");
  • 89. } int main() { greeting(); return 0; } Parts of Function 1. Function prototype 2. Function definition 3. Function call 1. Function prototype: Code: dataType functionName (parameter list) Example of function prototype: Code: void func() int func() void func(int ) int func(int , int ) Explanation for each is provided as follows: void func() - You cannot return any value from this function to caller function, as return type is void. If you try to return any value, error will occur. No parameter can be received by this function, as parameter list is empty.
  • 90. int func() You can return only integer value from this function to caller function. Trying to return value of any other data type will cause some error. No parameter can be received by this function, as parameter list is empty. void func(int a) - Look at the parameter in the function. It means the function receives one parameter, the data type of which is integer. While calling this function, you must send only one parameter of integer type. This function returns no value to the caller. int func(int , int ) - You can send more than one parameter while calling a function. Look at the function stated above. It receives two parameter of type integer. It also returns an integer value to the caller function. double func(int , double) - You can send different types of parameter in one function. In the above function, two parameters can be received. The first one should be of integer type and second one of double type. After doing all operations, according to prototype of this function, a double value must be returned to the caller function. 2. Function definition: Function definition is the body of the function. Code: void greeting() { printf("Hello Friend");
  • 91. } Here, void greeting() is the prototype of the function. Function body is the statement(s) between two curly braces{}. 3. Function call You can call a function by function name and parameter list, like this: Code: functionName(parameter1,…parameterN) Function calling statement must match with the function prototype. Function Parameters When a function is called with parameter(s), it can pass the parameters in two way: 1. By Value 2. By pointer 1. By Value In this type of calling, called function get the value of parameters from caller function and receive it with some variable. This variable works like local variable for the called function. So, any changes made in this variable is valid only for the called function, the caller does not get the change.
  • 92. Code: void changeVal(int a,int b) { if(a >= b) b = 0; else a = 0; } int main() { int x,y,bigger; printf("Enter x:"); scanf("%d",&x); printf("Enter y:"); scanf("%d",&y); changeVal(x,y); printf("After returning from changeVal function:n"); printf("x = %d, y = %d",x,y); } Output: Code: Enter x:25 Enter y:40 After returning from changeVal function: x = 25, y = 40 In the above example, changeaVal function get called from main function with x and y value. This values are received by
  • 93. changeaVal with variable a and b. Then values of this variable get changed by changeaVal . But after returning to main function, value of x and y remains the same. The changes made by changeaVal function are local to this function. 2. By Pointer In this type of calling, called function gets the memory of parameters from caller function and receives it with some pointers to that addresses. So, when any change is made, value of the memory address gets changed. So, the caller function also gets the effect of changed value. Code: void changeVal(int *a,int *b) { if(*a > *b) *b = 0; else *a = 0; } int main() { int x,y,bigger; printf("Enter x:"); scanf("%d",&x); printf("Enter y:"); scanf("%d",&y); changeVal(&x,&y); printf("After returning from changeVal function:n");
  • 94. printf("x = %d, y = %d",x,y); } Output: Code: Enter x:25 Enter y:40 After returning from changeVal function: x = 0, y = 40 Here we can see that main function also get the changes which is made by changeVal function. Nested function call Sometimes while one function calls another one, the called function also calls another function to perform its task. It works like this:
  • 95. The example given below illustrates the whole picture. Here, main function calls the getArea function. But to calculate area, you need to know length and width. So, before returning to main , getArea calls getLength and getWidth. getLength and getWidth function individually returns length and width to
  • 96. getArea function. getArea then calculates the area and returns the area to main . Code: int getWidth() { int wd=0; printf("Enter width:"); scanf("%d",&wd); return wd; } int getLength() { int len =0; printf("Enter length:"); scanf("%d",&len); return len; } int getArea() { int length, height =0; length = getLength(); height = getWidth(); return length*height; } int main() { int area; area = getArea(); printf("Area is: %d",area);
  • 97. } Return from function: By executing return statement, execution returns from the called function to caller function. If there are multiple return statements, only one out of them is executed and the rest are ignored. Code: int getBigger(int a,int b) { if(a > b) return a; else return b; } int main() { int x,y,bigger; printf("Enter x:"); scanf("%d",&x); printf("Enter y:"); scanf("%d",&y); bigger = getBigger(x,y); printf("bigger num is: %d",bigger); }
  • 98. Here, in getBigger function, we can see two return statements. When any return statement is executed, no other statements are executed. Execution returns to the caller. Recursive function When a function is called by itself, then it is called recursive function. Recursive function has two parts: 1. Base case 2. Recursive case General concept of recursive function is like this: it will call itself with some parameters until the base case is true. Code: int recursiveAdd(int num) { if(num < 1) return num; else return (num+recursiveAdd(num-1)); } int main() { int input, sum = 0; printf("Enter number: "); scanf("%d",&input); sum = input + recursiveAdd(input-1); printf("Sum of number from 1 to %d is %d",input,sum);
  • 99. } The base case is: Code: if(num < 1) return num; And the recursive case is: Code: else return (num+recursiveAdd(num-1)); As long as the number is greater or equal to 1, the function continues to call itself. When the number is less than 1, then base case is executed the recursion is stopped. Most popular example of recursive function is to find out the factorial. Code: int getFactorial(int num) { if(num <= 1) return 1; else return (num * getFactorial(num-1)); } int main() { int input, factorial = 0;
  • 100. printf("Enter number: "); scanf("%d",&input); factorial = input * getFactorial(input-1); printf("Factorial of number %d is %d",input,factorial); } Infinite recursion: What if any recursive function doesn’t have any base case? Code: int recursiveFunc(int num) { recursiveFunc(num-1); } Here, no base case exists for recursiveFunc. So every time it is called by itself, it never exits. It results an infinity loop. Another scenario: Let, you wrote a base case that will never be executed. What will happen? Code: int recursiveFunc(int num) { if(num < 1) return num; else recursiveFunc(num+1);
  • 101. } int main() { int input, result = 0; printf("Enter number: "); scanf("%d",&input); result = recursiveFunc(input-1); } If user gives a positive number as input, what will happen? In recursiveFunc, an integer with positive value will be passed. First time, base case will be false, so it will make a recursive call with(n+1). And if you have a closer look, every time the value of parameter will be increased by 1. So it will never be less than 1. Every time the base case fails, results an infinite recursion. Direct and indirect recursion: When a function calls itself, it is called direct recursion. But if two function individually call one another, what will happen? Code: int getX() { getY(); } int getY() { getX();
  • 102. } Here, getX() calls getY(). When execution comes in getY(), it again calls getX(), and getX() calls getY(). This process continues, resulting an recursion. Sometimes, this type of indirect recursion also results an infinite recursion. Benefits of using function: 1. Program can be modularized into small parts 2. Different function can be independently developed according to the requirement 3. Increases readability and re-usability C Arrays Contributed by msfq17a () On 30th December, 2013 This is an article on C Arrays in C. Array is a data structure consists of a group of elements of same data type. We can think it as collection of variable of similar data type. Array prototype: Code: Data_type array_name[array_size] Example:
  • 103. Suppose you have a team of 10 employees. Id is given for every employee. You want to store id, age and salary of each employee. How will you do that? From the concept of variable, you can declare 10 variables to store individual id, like: intemployeeId0, employeeId1, employeeId2, employeeId3, employeeId4, employeeId5, employeeId6, employeeId7, employeeId8, employeeId9; Isn’t that a hazard? You are declaring ten variables only for storing ten ids. It is the case where array facilitates you. Instead of ten variables, you can declare only one variable and store the same type of data in it. Code: int employeeId[10]; Here, employeeId is an array of integer type of size 10. Array Indexing: So, if array is able to address different data of same type with same variable name, how does it maintain it? Indexing does the task. For the array declared above, every employee id can be accessed by the index of the array. The elements are: employeeId[0], employeeId[1], employeeId[2], employeeId[3], employeeId[4], employeeId[5], employeeId[6], employeeId[7], employeeId[8], employeeId[9] 0,1,2…9 are the index of individual element. If the size of the
  • 104. array is n, then the index of array elements are from 0 to n-1. You can use array of age and salary of the employees as well. Code: int employeeAge[10], float employeeSalary[10] Array Memory Allocation: The whole array is stored in a single contiguous memory block. Let, you have an array of integer: Code: int employeeId[10]; If size of an integer is 2 byte, then 20(10*2) bytes will be required to store this array in memory and these 20 bytes must be contiguous. Address of the first element is called the base address of the array. Address of ith element of the array can be achieved by following formula:
  • 105. Address of i element = Address of base + size of element * i; Array initialization There are different ways to assign values to elements of an array .  Static initialization  Assigning values from Standard Input  Default Array initialization 1. Static initialization: Code: int employeeAge[10] = {35,30,30,30,28,28,25,34,35,40}; 2. Assigning values from Standard Input: Suppose you have an array for age of employee, int employeeAge[10] . You want to take input and store the value in the array. You can use for loop to initialize the array. Code: int employeeAge[10], count, totalScore = 0; for(count = 0; count < 10; count++) { printf("Enter Age: employeeAge[%d]:", count); scanf("%d",& employeeAge[count]); }
  • 106. 3. Default Array initialization: Code: int main() { int arr [5] = {20}; int count; for(count = 0; count < 5; count++) { printf("%dn", arr [count]); } } Output: Code: 20 0 0 0 0 Here, array size is 5. But we have initialized it with only one value {20}, instead of five. So, first element of the array, arr[0] get initialized with 20 and other elements are initialized with 0. Accessing array elements Suppose you have an array, which is initialized. Now you want
  • 107. to see the value of each element. Here is an example for doing this stuff: Code: int main() { int count; int employeeAge[10] = {35,30,30,30,28,28,25,34,35,40}; printf("here is the individual age of employees:n"); for(count = 0; count < 10; count++) { printf("employee[%d]: %dn", count,employeeAge[count]); } } Passing Arrays to Function There are two ways of doing this: 1. Array element as parameter 2. Whole array as parameter 1. Array element as parameter If you want to send some element of an array to a function, you can specify the elements by their index. In the example given below, 1st and 2nd element of the array byteVal[8] are sent to addVal function. The parameters are byteVal[0] and byteVal[1]. Accordiingly, 2nd and 5th element of byteVal[8] array are sent to subtractVal function. Code: int addVal(int x, int y)
  • 108. { int sum = x+y; return sum; } int subtractVal(int x, int y) { int sub = x - y; return sub; } int main() { int byteVal[8] = {40,10,250,5,190,150,80,200}; int addByteVal, subByteVal; addByteVal = addVal(byteVal[0],byteVal[1]); subByteVal = subtractVal(byteVal[1],byteVal[4]); printf("addition result : %d, subtraction result: %d",addByteVal, subByteVal); } 2. Whole array as parameter So, when you want to call a function with an array as argument, just write the array name. The parameter passing procedure is just like the variable passing. The difference is in how the called function receives the array. To receive an array, you have to write the array name with array notation[]. It means that the received parameter is an array. You do not need to define the array size here.
  • 109. In the example given below, array byteVal is passed to the function showByteVal by only the name and received with an integer array, int getByte[] . Code: int showByteVal(int getByte[]) { int count; printf("Array of byte value recieved. Values are:n"); for(count = 0; count < 8; count++) { printf("%dn",getByte[count]); } } int main() { int byteVal[8] = {40,10,250,5,190,150,80,200}; showByteVal(byteVal); } Why array passed to function changes its value? Suppose you send an array or any array elements to a function. Then you make some operation on the array elements and change value of the element. When the function returns, the data passed as array parameter is changed. Let’s see: Code: int changeByteVal(int getByte[]) {
  • 110. int count; printf("Array of byte value recieved. Values are:n"); for(count= 0; count < 8; count++) { printf("%dn",getByte[count]); } getByte[0] = getByte[1] + getByte[2]; } int main() { int loopCount; int byteVal[8] = {40,10,250,5,190,150,80,200}; changeByteVal(byteVal); printf("returned from changeByteVal function. Now values are:n"); for(loopCount= 0; loopCount < 8; loopCount++) { printf("%dn",byteVal[loopCount]); } } Output: Code: Array of byte value received. Values are: 40 10 250 5 190
  • 111. 150 80 200 returned from changeByteVal function. Now values are: 260 10 250 5 190 150 80 200 In the above program the first element of byteVal array, byteVal[0] is initialized with value 40. The array is sent to changeByteVal function. Here, value of byteVal[0] has been changed to 260. When we return to caller function, we print the element of the array and experience that value of byteVal[0] is now 260. When an array is sent to a function, it is the base address of the array is sent. The base address received by the called function makes operation on the variables memory and so the original value gets changed. So, you will always get the changed value. 2D Arrays Array can be multi dimensional. In this section, we will discuss about two-dimensional array.
  • 112. Prototype: Prototype of 2d array is: Code: DataType arrayName [rowSize][columnSize] Think of an array of 2*2 dimension. It is declared as: Code: int matrix[2][2]; Visualization is like this: Elements of this 2d array are: Code: matrix[0][0] = 0 matrix[0][1] = 1
  • 113. matrix[1][0] = 2 matrix[1][1] = 3 Suppose you have three teams and every team contains five members. You want to store the age of each member of every team. Then you should declare a two dimensional array of 3*5 size. int memberAge[3][5] Here, 3 is team number and 5 is number of members of every team. You can initialize and access age of each member of each team by this 2d array. 2D Array Initialization 2d array is initialized in the same ways as array. 1. Static initialization 2. Assigning values from Standard Input 3. Default Array initialization 1. Static initialization: 2d array can be statically initialized in 2 different ways: Way 1: int age[2][3]= {40,35,30,42,33,25}; Way 2: int age[2][3] = {{40,35,30},{42,33,25}}; 2. Assigning values from Standard Input:
  • 114. How to initialize every element of a 2d array from standard input? Let’s see: Code: #define ROWSIZE 2 #define COLSIZE 3 int main() { int row, col; int age[ROWSIZE][ COLSIZE]; for(row = 0; row < ROWSIZE; row++) for(col =0; col < COLSIZE; col++) scanf("%d",&age[row][col]); } 3. Default Array initialization This is same as single dimension array where the specified values are initialized and rest is all 0. Accessing 2d array elements If you have an initialized 2d array and want to get the values, you can act like this: Code: #define ROWSIZE 2 #define COLSIZE 3 int main() { int row, col;
  • 115. int age[ROWSIZE][ COLSIZE] = {40,35,30,42,33,25}; for(row = 0; row < ROWSIZE; row++) for(col =0; col < COLSIZE; col++) printf("Index[%d][%d] : %dn",row,col,age[row][col]); } Use of Arrays Array is used for different operations. In some searching and sorting algorithm, array is very important and useful. We are going to watch how array facilitates linear search operation. Linear search: Let you have a list of roll numbers who have passed in the last exam. Now, some students come to you, tell their rolls and ask you whether they are in the pass list. The list is not sorted in increasing or decreasing order yet. How will you search their roll? For every student, you will start from the beginning of your list and search every element of the list throughout the end. If roll number is found, you will stop and tell that he/she has passed. Otherwise you would inform the negative result. This type of searching is called linear search. Here is a way of implementing linear search using array: Code: #define SIZE 4 int main()
  • 116. { int i,searchNum; int arrayOfNum[SIZE]; int flag = 0; int iterate = SIZE - 1; printf("Enter %d elements of array:n",SIZE); for(i =0; i < SIZE; i++) { printf("narrayOfNum[%d]:",i); scanf("%d",&arrayOfNum[i]); } printf("Enter the element you want to search:"); scanf("%d",&searchNum); for(i = 0; i < SIZE; i++) { if(arrayOfNum[i] == searchNum) { printf("%d found in arrayOfNum[%d]",searchNum,i); flag = 1; break; } } if(flag == 0) printf("Not foundn"); } Use of 2d Array 2d array can be used for different advanced operations. Out of them, most common example is matrix operation. We can
  • 117. perform any matrix operation using 2d arrays. We are going to explain matrix addition operation using 2d arrays. Matrix Addition Suppose A and B are two matrices. We have to perform matrix addition and save the result in another matrix. Let the new matrix is C. So, the operation we are going to perform is: C = A + B. Code: #define ROWSIZE 2 #define COLSIZE 3 int main() { int row, col; int A[ROWSIZE][COLSIZE],B[ROWSIZE][COLSIZE],C[ROWSIZE][COLSIZE]; printf("Enter elements of matrix A:n"); for(row = 0; row < ROWSIZE; row++) for(col =0; col < COLSIZE; col++) { printf("nA[%d][%d]:",row,col); scanf("%d",&A[row][col]); } printf("Enter elements of matrix B:n"); for(row = 0; row < ROWSIZE; row++) for(col =0; col < COLSIZE; col++) {
  • 118. printf("nB[%d][%d]:",row,col); scanf("%d",&B[row][col]); } printf("After performing operation C = A+B:n"); for(row = 0; row < ROWSIZE; row++) for(col =0; col < COLSIZE; col++) { C[row][col] = A[row][col] + B[row][col]; printf("C[%d][%d] : %dn",row,col,C[row][col]); } } Advantages of Arrays 1. Group of similar objects can be used by single variable and different index. 2. Multi dimensional arrays is possible 3. Accessing array element is not sequential and so operations like searching, sorting are faster. Disadvantages of Arrays 1. Array size is static in C. Allocated memory cannot be increased or decreased with arrays and so size of array has to to be known before any operation. For dynamic size we have to be using pointers. 2. Removing array elements from between means the complete array needs to be shifted which is a costly operation.