understanding c file handling functions with examples

133
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

Upload: muhammed-thanveer-danish-melayi

Post on 20-Jan-2015

358 views

Category:

Documents


2 download

DESCRIPTION

 

TRANSCRIPT

Page 1: Understanding c file handling functions with examples

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

Page 2: Understanding c file handling functions with examples

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 

Page 3: Understanding c file handling functions with examples

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:

Page 4: Understanding c file handling functions with examples

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

Page 5: Understanding c file handling functions with examples

“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. 

Page 6: Understanding c file handling functions with examples

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: integerValue: 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

Page 7: Understanding c file handling functions with examples

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 readOn 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);

Page 8: Understanding c file handling functions with examples

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 );

Page 9: Understanding c file handling functions with examples

Parameters

character: The character to be written in the file.stream: pointer to the file in which data will be written.

Return

Type: integerValue: On success Integer value of the character which is writtenOn 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);

Page 10: Understanding c file handling functions with examples

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: integerValue: On Success integer value of the character which is readOn Failure Null pointer, setting the error indicator

It returns the character which is currently pointed by the FILE pointer.

Page 11: Understanding c file handling functions with examples

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:

Page 12: Understanding c file handling functions with examples

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: integerValue: On success number of characters which is writtenOn 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");

}

Page 13: Understanding c file handling functions with examples

else

{

for(count = 0; count < 4; count++)

{

fprintf(fp,"%-10s %-10s\n",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.

Page 14: Understanding c file handling functions with examples

Return 

Type: integerValue: On success number of arguments which is filledOn 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%-10s\n",bookName,bookAuthor);

}

}

}

Page 15: Understanding c file handling functions with examples

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_tValue: On success number of elements which are successfully writtenOn failure zero (0) if the size or count is 0. Error indicator is set.

Example

Code:

Page 16: Understanding c file handling functions with examples

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;

Page 17: Understanding c file handling functions with examples

}

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_tValue: 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.

Page 18: Understanding c file handling functions with examples

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 %-10s\n",banglaBook.title,banglaBook.author);

}

}

fclose(fp);

return 0;

Page 19: Understanding c file handling functions with examples

}

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.

Page 20: Understanding c file handling functions with examples

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 console\n");

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()

Page 21: Understanding c file handling functions with examples

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);

Page 22: Understanding c file handling functions with examples

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:

Page 23: Understanding c file handling functions with examples

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.

Page 24: Understanding c file handling functions with examples

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 fileSEEK_CUR - Current position of the file pointerSEEK_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;

Page 25: Understanding c file handling functions with examples

}

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 bytesOn failure -1. System specific error no is set

Example

Code:

int main () {

FILE * fp;

long int len;

Page 26: Understanding c file handling functions with examples

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.

Page 27: Understanding c file handling functions with examples

Return 

Type: integerValue: 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: integerValue: On success zero(0).On failure system specific error no. 

Example fgetpos fsetpos

Page 28: Understanding c file handling functions with examples

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:

Page 29: Understanding c file handling functions with examples

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.

Page 30: Understanding c file handling functions with examples

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:

Page 31: Understanding c file handling functions with examples

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:

Page 32: Understanding c file handling functions with examples

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

Page 33: Understanding c file handling functions with examples

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:

Page 34: Understanding c file handling functions with examples

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__

Page 35: Understanding c file handling functions with examples

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

Page 36: Understanding c file handling functions with examples

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");

Page 37: Understanding c file handling functions with examples

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>

Page 38: Understanding c file handling functions with examples

#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 FD\n");

exit (1);

}

write (fd, "Writing using FD\n", 17);

fp = fdopen(fd, "a");

fprintf(fp, "Writing using File Ptr\n");

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

Page 39: Understanding c file handling functions with examples

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 FP\n");

exit (1);

}

fprintf(fp, "Writing using File Ptr\n");

fd = fileno (fp);

write (fd, "Writing using FD\n", 17);

fclose (fp);

close(fd);

return 0;

Page 40: Understanding c file handling functions with examples

}

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 ;

Page 41: Understanding c file handling functions with examples

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

Page 42: Understanding c file handling functions with examples

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.

Page 43: Understanding c file handling functions with examples

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

Page 44: Understanding c file handling functions with examples

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.

Page 45: Understanding c file handling functions with examples

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 )

Page 46: Understanding c file handling functions with examples

        {

               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

Page 47: Understanding c file handling functions with examples

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

Page 48: Understanding c file handling functions with examples

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);

}

Page 49: Understanding c file handling functions with examples

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

Page 50: Understanding c file handling functions with examples

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

Page 51: Understanding c file handling functions with examples

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("%d\t%d\n",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()

Page 52: Understanding c file handling functions with examples

{

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, 3Output: * * * 

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:

Page 53: Understanding c file handling functions with examples

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]= %d\n",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:

Page 54: Understanding c file handling functions with examples

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:

Page 55: Understanding c file handling functions with examples

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 chances\

n",maxChances);

while(guessNum != secretNum && usedChance < maxChances )

Page 56: Understanding c file handling functions with examples

{

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);

}

}

Page 57: Understanding c file handling functions with examples

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("%d\t",&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{

Page 58: Understanding c file handling functions with examples

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("%d\n",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

Page 59: Understanding c file handling functions with examples

choice, does some operation. For example, some menu like this:

Select any one from the menu:1. Add numbers.2. Subtract numbers3. 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 operation\n");

printf("1.Addition\n");

printf("2.Subtraction\n");

printf("3.Multiplication\n");

printf("4.Division\n");

printf("5.Exit Program\n");

scanf("%d", &option);

printf("\n");

Page 60: Understanding c file handling functions with examples

switch(option)

{

case 1:

printf("Summation result is =%.2f\n",num1+num2);

break;

case 2:

printf("Subtraction result is =%.2f\n",num1-num2);

break;

case 3:

printf("Multiplication result is =%.2f\

n",num1*num2);

break;

case 4:

printf("Division result is =%.2f\n",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.

Page 61: Understanding c file handling functions with examples

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

Page 62: Understanding c file handling functions with examples

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:

Page 63: Understanding c file handling functions with examples

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

Page 64: Understanding c file handling functions with examples

(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;

};

Page 65: Understanding c file handling functions with examples

Different section of structure: definition

Every structure consists of three parts:1. The keyword struct2. Tag3. 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:

Page 66: Understanding c file handling functions with examples

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

Page 67: Understanding c file handling functions with examples

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);

}

Page 68: Understanding c file handling functions with examples

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:

Page 69: Understanding c file handling functions with examples

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;

Page 70: Understanding c file handling functions with examples

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;

Page 71: Understanding c file handling functions with examples

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:

Page 72: Understanding c file handling functions with examples

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 students\n");

printf("Name\tId\n");

printf("---------------\n");

for(loopCount = 0; loopCount < 3; loopCount++)

{

printf("%s\t%d\n",CSE[loopCount].name, CSE[loopCount].id);

}

}

Page 73: Understanding c file handling functions with examples

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:

Page 74: Understanding c file handling functions with examples

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(->)

Page 75: Understanding c file handling functions with examples

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;

Page 76: Understanding c file handling functions with examples

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:

Page 77: Understanding c file handling functions with examples

struct student

{

char* name;

int id;

};

void showStudentInfo(struct student st)

{

printf("Student Name: %s\n",st.name);

printf("Student Id: %d\n",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:

Page 78: Understanding c file handling functions with examples

struct student

{

char* name;

int id;

};

void showStudentInfo(struct student st)

{

st.name = "J. Richards";

st.id = 110;

printf("After changing valu in showStudentInfo\n");

printf("Student Name: %s\n",st.name);

printf("Student Id: %d\n",st.id);

}

int main()

{

struct student student1;

student1.name = "John Richards";

student1.id = 109;

showStudentInfo(student1);

printf("Back to main function\n");

printf("Student Name: %s\n",student1.name);

printf("Student Id: %d\n",student1.id);

}

The ouput would be like this.

Code:

After changing valu in showStudentInfo

Page 79: Understanding c file handling functions with examples

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 showStudentInfo\n");

printf("Student Name: %s\n",st->name);

printf("Student Id: %d\n",st->id);

}

int main()

Page 80: Understanding c file handling functions with examples

{

struct student student1;

student1.name = "John Richards";

student1.id = 109;

showStudentInfo(&student1);

printf("Back to main function\n");

printf("Student Name: %s\n",student1.name);

printf("Student Id: %d\n",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:

Page 81: Understanding c file handling functions with examples

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

Page 82: Understanding c file handling functions with examples

{

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:

Page 83: Understanding c file handling functions with examples

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:

Page 84: Understanding c file handling functions with examples

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

Page 85: Understanding c file handling functions with examples

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;

Page 86: Understanding c file handling functions with examples

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).

Page 87: Understanding c file handling functions with examples

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:

Page 88: Understanding c file handling functions with examples

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 function2. User defined function

1. Library function:

Every language is accompanied by a collection of library

Page 89: Understanding c file handling functions with examples

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

Page 90: Understanding c file handling functions with examples

1. Function prototype2. Function definition3. 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

Page 91: Understanding c file handling functions with examples

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 bereturned 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

Page 92: Understanding c file handling functions with examples

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 Value2. 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;

Page 93: Understanding c file handling functions with examples

}

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

Page 94: Understanding c file handling functions with examples

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:

Page 95: Understanding c file handling functions with examples

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:

Page 96: Understanding c file handling functions with examples

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

Page 97: Understanding c file handling functions with examples

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);

Page 98: Understanding c file handling functions with examples

}

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);

}

Page 99: Understanding c file handling functions with examples

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 case2. 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);

Page 100: Understanding c file handling functions with examples

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()

Page 101: Understanding c file handling functions with examples

{

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)

Page 102: Understanding c file handling functions with examples

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();

Page 103: Understanding c file handling functions with examples

}

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 parts2. Different function can be independently developed according to

the requirement3. 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:

Page 104: Understanding c file handling functions with examples

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:

Page 105: Understanding c file handling functions with examples

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.

Page 106: Understanding c file handling functions with examples

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);

Page 107: Understanding c file handling functions with examples

scanf("%d",& employeeAge[count]);

}

3. Default Array initialization:

Code:

int main()

{

int arr [5] = {20};

int count;

for(count = 0; count < 5; count++)

{

printf("%d\n", 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

Page 108: Understanding c file handling functions with examples

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]: %d\n", count,employeeAge[count]);

}

}

Passing Arrays to Function

There are two ways of doing this:1. Array element as parameter2. 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].

Page 109: Understanding c file handling functions with examples

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

Page 110: Understanding c file handling functions with examples

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("%d\n",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

Page 111: Understanding c file handling functions with examples

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("%d\n",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("%d\n",byteVal[loopCount]);

}

}

Output:

Code:

Page 112: Understanding c file handling functions with examples

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.

Page 113: Understanding c file handling functions with examples

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: 

Page 114: Understanding c file handling functions with examples

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 initialization2. Assigning values from Standard Input3. 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};

Page 115: Understanding c file handling functions with examples

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:

Page 116: Understanding c file handling functions with examples

#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] : %d\n",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

Page 117: Understanding c file handling functions with examples

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 found\n");

Page 118: Understanding c file handling functions with examples

}

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++)

{

Page 119: Understanding c file handling functions with examples

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] : %d\n",row,col,C[row][col]);

}

}

Advantages of Arrays1. Group of similar objects can be used by single variable and

different index.2. Multi dimensional arrays is possible3. Accessing array element is not sequential and so operations

like searching, sorting are faster.

Disadvantages of Arrays

Page 120: Understanding c file handling functions with examples

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.