File
File
ALLOCATION
Array of Structure and pointers
File Handling
Opening & Closing file
fread(), fwrite()
Dynamic Memory Allocation
ICE
ARRAY OF STRUCTURE
AND POINTERS
3.1.1 ARRAY OF STRUCTURES
Definition:
Structure is used to store the information of One particular
object but if we need to store such 100 objects then Array of
Structure is used.
Example :
struct Bookinfo
{ 1.Here Book structure is used to
Store the information of one Book.
char[20] bname;
2. In case if we need to store the
int pages; Information of 100 books then
int price; Array of Structure is used.
} 3. b1[0] stores the Information of
1st Book , b1[1] stores the
Book[100]; information of 2nd Book and So on
We can store the information of 100
books. 4
ICE
3.1.2 POINTERS TO STRUCTURES
Pointer to Structure in C Programming
Address of Pointer variable can be obtained using ‘&’operator.
Address of such Structure can be assigned to the Pointer
variable .
Pointer Variable which stores the address of Structure must
be declared as Pointer to Structure .
Pointer to Structure Syntax :
struct student_database
{
char name[10];
int roll;
int marks;
}stud1;
struct student_database *ptr;
5
ptr = &stud1; How to Access Structure Members?
ICE
Simple program without Pointer variable:
#include <stdio.h>
int main()
{
struct student database
{
char name[10];
int roll; int marks; Output:
}stud1;
Roll Number : 10
stud1.roll = 10;
Marks of Student : 90
stud1.marks = 90;
printf("Roll Number : %d",stud1.roll);
printf("Marks of Student : %d",stud1.marks);
return 0;
} 6
ICE
Simple program with Pointer
#include
<stdio.h> variable:
int main(int argc, char *argv[])
{
struct student_database
{
char name[10];
int roll;
int marks; Output:
}stud1 = {"Pritesh",90,90};
struct student_database *ptr; Roll Number : 90
Marks of Student : 90
ptr = &stud1;
printf("Roll Number : %d",(*ptr).roll);
printf("Marks of Student : %d",(*ptr).marks);
return 0;
7
}
ICE
3.1.3 ARRAY O F POINTERS
Array of pointers
ICE
FILE HANDLING
3.2.1 INTRODUCTION OF FILE
HANDLING
Drawbacks of Traditional I/O System.
ICE
File handling in C :
1. New way of dealing with data is file handling.
2. Data is stored onto the disk and can be retrieve whenever
require.
3. Output of the program may be stored onto the disk
4. In C we have many functions that deals with file handling
5. A file is a collection of bytes stored on a secondary
storagedevice (generally a disk)
ICE
12
ICE
3.2.2 OPENING & CLOSING FILE
Opening Files
We can use the fopen( ) function to create a new file or to
open an existing file. This call will initialize an object of the
type FILE, which contains all the information necessary to
control the stream. The prototype of this function call is as
follows −
ICE
Mode Description
r Opens an existing text file for reading purpose.
w Opens a text file for writing. If it does not exist, then a new file
is created. Here your program will start writing content from
the beginning of the file.
a Opens a text file for w riting in appending mode. If it does not
exist, then a new file is created. Here your program w ill start
appending content in the existing file content.
r+ Opens a text file for both reading and wr iting.
w+ Opens a text file for both reading and writing. It first truncates
the file to zero length if it exists, otherwise creates a file if it
does not exist.
a+ Opens a text file for both reading and writing. It creates the
file if it does not exist. The reading w ill start from the
beginning but writing can only be appended. 14
ICE
If you are going to handle binary files, then we will use
following access modes instead of the above mentioned
ones Description
Mode
rb Opens an existing text file for reading purpose.
wb Opens a text file for writing. If it does not exist, then a new file is
created. Here your program w ill start writing content from the
beginning of the file.
ab Opens a text file for w riting in appending mode. If it does not exist,
then a new file is created. Here your program w ill start appending
content in the existing file content.
r+b Opens a text file for both reading and wr iting.
w+b Opens a text file for both reading and wr iting. It first truncates the file
to zero length if it exists, otherwise creates a file if it does not exist.
a+b Opens a text file for both reading and writing. It creates the file if it
does not exist. The reading w ill start from the beginning but writing
can only be appended.
15
ICE
Closing file
To close a file, use the fclose( ) function. The prototype of
this function is −
16
ICE
Writing a File
Following is the simplest function to write individual
characters to a stream −
int fputc( int c, FILE *fp );
The function fputc() writes the character value of the
argument c to the output stream referenced by fp. It
returns the written character written on success
otherwise EOF if there is an error. You can use the
following functions to write a null-terminated string to a
stream −
int fputs( const char *s, FILE *fp );
The function fputs() writes the string s to the output
stream referenced by fp. It returns a non-negative value on
success, otherwise EOF is returned in case of any error. 17
ICE
CONT..
#include <stdio.h>
main()
{
FILE *fp; fp = fopen("/tmp/test.txt", "w+");
fprintf(fp, "This is testing for fprintf...\n");
fputs("This is testing for fputs...\n", fp);
fclose(fp);
}
ICE
CONT..
Reading a File
ICE
CONT..
20
ICE
main()
{
CONT..
FILE *fp;
char buff[255];
fp = fopen("/tmp/test.txt", "r");
fscanf(fp, "%s", buff); printf("1 : %s\n", buff );
fgets(buff, 255, (FILE*)fp); printf("2: %s\n",buff );
fgets(buff, 255, (FILE*)fp); printf("3: %s\n",buff );
fclose(fp);
Output:-
}
1 : This
2: is testing for fprintf...
3: This is testing for fputs...
Note: First, fscanf() read just This because after that, it
encountered a space, second call is for fgets() which reads the
remaining line till it encountered end of line. Finally, the last
call fgets() reads the second line completely.
21
3.2.3 BINARY & TEXT FILES
Definition
Text File:-A text file is a file that is properly understood
as a sequence of character data, separated into lines. when
a text file is displayed as a sequence of characters, it is
easily human-readable.
Binary File:- A binary file is anything else. A binary file
will include some data that is not written using a
character-encoding standard some number would be
represented using binary within the file, instead of using
the character representation of its various digits
22
ICE
FPRINTF(), FSCANF(),
FEOF()
Lecture no.- 30,
UNIT- III
3.2.4 FPRINTF(), FSCANF(), FEOF()
C library function - fprintf()
Description
The C library function int fprintf(FILE *stream, const char
*format, ...) sends formatted output to a stream.
Declaration
int fprintf(FILE *stream, const char *format, ...)
Parameters
stream − This is the pointer to a FILE object that identifies the
stream.
format − This is the C string that contains the text to be written
to the stream. It can optionally contain embedded format tags
that are replaced by the values specified in subsequent
additional arguments and formatted as requested. Format tags
prototype is %[flags][width][.precision][length]specifier ,
which is explained in next slide. 24
ICE
specifier Output
c Character
d or i Signed decimal integer
e Scientific notation (mantissa/exponent) using e
character
E Scientific notation (mantissa/exponent) using E
character
f Decimal floating point
g Uses the shorter of %e or %f
G Uses the shorter of %E or %f
25
ICE
CONT..
o Signed octal
s String of characters
u U nsigned decimal integer
x U nsigned hexadecimal integer
X U nsigned hexadecimal integer (capital letters)
p Pointer address
n N othing printed
% Character
26
ICE
Example:
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE * fp; fp = fopen ("file.txt", "w+");
fprintf(fp, "%s %s %s %d", "We", "are", "in", 2012);
fclose(fp);
return(0);
}
Let us compile and run the above program that will create
file file.txt with the following content − a
We are in 2012 27
ICE
C library function - fscanf(),
Description
The C library function int fscanf(FILE *stream, const
char *format, ...) reads formatted input from a stream.
Declaration
Following is the declaration for fscanf() function.
int fscanf(FILE *stream, const char *format, ...)
Parameters
stream − This is the pointer to a F IL E object that identifies the
stream.
format − This is the C string that contains one or more of the
following items − Whitespace character, Non-whitespace
character and Format specifiers. A format specifier will be
as [=%[*][width][modifiers]type=], which is explained in
28
next slide.
ICE
Argument Description
* This is an optional starting asterisk indicates that the
data is to be read from the stream but ignored, i.e. it is
not stored in the corresponding argument.
width This specifies the maximum number of characters to be
read in the current reading operation.
modifiers Specifies a size different from int (in the case of d, i and
n), unsigned int (in the case of o, u and x) or float (in the
case of e, f and g) for the data pointed by the
corresponding additional argument: h : short int (for d, i
and n), or unsigned short int (for o, u and x) l : long int
(for d, i and n), or unsigned long int (for o, u and x), or
double (for e, f and g) L : long double (for e, f and g)
type A character specifying the type of data to be read and
how it is expected to be read. See next table. 29
ICE
Example
#include <stdio.h>
#include <stdlib.h>
int main()
{ Output:
char str1[10], Read String1 |We|
str2[10], str3[10]; Read String2 |are|
Read String3 |in|
int year;
Read Integer |
FILE * fp; fp = fopen ("file.txt", "w+");
2012|
fputs("We are in 2012", fp);
rewind(fp);
fscanf(fp, "%s %s %s %d", str1, str2, str3, &year);
printf("Read String1 |%s|\n", str1 );
printf("Read String2 |%s|\n", str2 );
printf("Read String3 |%s|\n", str3 );
printf("Read Integer |%d|\n", year );
fclose(fp);
return(0); } 30
ICE
C LIBRARY FUNCTION - FEOF()
Description
The C library function int feof(FILE *stream) tests the end-
of-file indicator for the given stream.
Declaration
Following is the declaration for feof() function.
int feof(FILE *stream)Parameter
stream − This is the pointer to a FILE object that identifies
the stream.
Return Value
This function returns a non-zero value when End-of-File
indicator associated with the stream is set, else zero is
returned.
31
ICE
EXAMPLE:
#include <stdio.h>
int main ()
{
FILE *fp; int c; fp = fopen("file.txt","r");
if(fp == NULL)
{
perror("Error in opening file");
return(-1);
} while(1)
{ c = fgetc(fp);
NOTE:Assuming we have a text file file.txt,
if( feof(fp) ) which has the following content. This file will be
used as an input for our example program −
{ break ; This is Imperial
}
printf("%c", c);
} fclose(fp); Output:
This is Imperial
return(0);
32
}
ICE
FREAD(), FWRITE()
ICE
Example
#include <stdio.h>
#include <string.h>
int main()
{
FILE *fp; char c[] = "this is Indrajeet";
char buffer[100]; /* Open file for both reading and writing */
fp = fopen("file.txt", "w+"); /* Write data to the file */
fwrite(c, strlen(c) + 1, 1, fp); /* Seek to the beginning of the file */
fseek(fp, SEEK_SET, 0); /* Read and display data */
fread(buffer, strlen(c)+1, 1, fp);
printf("%s\n", buffer);
fclose(fp);
return(0);
}
Output:- this is Imperial
35
ICE
C library function - fwrite()
Description
The C library function size_t fwrite(const void *ptr, size_t size,
size_t nmemb, FILE *stream) writes data from the array pointed
to, by ptr to the given stream.
Declaration
size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)
Parameters
ptr − This is the pointer to the array of elements to be written.
size − This is the size in bytes of each element to be written.
nmemb − This is the number of elements, each one with a size
of size bytes.
stream − This is the pointer to a F IL E object that specifies an output 36
stream.
ICE
#include<stdio.h>
int main ()
{
FILE *fp; char str[] = "This is Arya First year Department";
fp = fopen( "file.txt" , "w" );
fwrite(str , 1 , sizeof(str) , fp );
fclose(fp);
return(0);
}
Note:- Let us compile and run the above program that will
create a file file.txt which will have following content −
This is Arya First year Department 37
ICE
Now let's see the content of the above file using the following
program
#include <stdio.h>
int main ()
{
FILE *fp; int c; fp = fopen("file.txt","r");
while(1)
{
c = fgetc(fp);
if( feof(fp) ) Output:
{ This is Arya First year
Department
break ;
}
printf("%c", c);
}
fclose(fp);
38
return(0);
ICE
3.2.8 SEQUENTIAL VS. RANDOM
ACCESS FILES
In computer programming, the two main types of file handling
are:
Sequential;
Random access.
Definition:
Sequential files are generally used in cases where the
program processes the data in sequential fashion – i.e.
a
counting words in a text file – although in some cases, random
access can be feigned by moving backwards and forwards over a
sequential file.
True random access file handling, however, only accesses the
file at the point at which the data should be read or written,
rather than having to process it sequentially. A hybrid
approach is also possible whereby a part of the file is used for
sequential access to locate something in the random access
portion of the file, in much the same way that a File Allocation 39
Table (FAT) works.
ICE
40
ICE
DYNAMIC MEMORY
ALLOCATION
3.3.1 DYNAMIC MEMORY
A L LO C AT I O N
C dynamic memory allocation refers to performing manual
memory management for dynamic memory allocation in the C
programming language via a group of functions in the C
standard library, namely malloc, realloc, calloc and free.
3.3.1.1 Malloc
Description
The C library function void *malloc(size_t size) allocates the
requested memory and returns a pointer to it.
Declaration
void *malloc(size_t size)
Parameters
size -- This is the size of the memory block, in bytes.
42
ICE
Example
#include <stdio.h> Output:
#include <stdlib.h> String = Imperial College,
int main() Address = 355090448
String = Imperial College,
{
Address = 355090448
char *str; /* Initial memory allocation */
str = (char *)
malloc(15);
strcpy(str, " Imperial College ");
printf("String = %s, Address = %u\n", str, str); /* Reallocating memory */
str = (char *) realloc(str, 25);
strcat(str, ".com");
printf("String = %s, Address = %u\n", str, str);
free(str);
return(0);
43
}
ICE
Definition:
When calloc is used to allocate a block of memory, the
allocated region is initialized to zeroes.
In contrast, malloc does not
touch the contents of the allocated block of memory, which
means it contains garbage values.
Description
The C library function void *calloc(size_t nitems, size_t
size)allocates the requested memory and returns a pointer to it.
The difference in malloc and calloc is that malloc does not set the
memory to zero where as calloc sets allocated memory to zero.
Declaration
46
ICE
Example
#include <stdio.h>
#include <stdlib.h>
Output:
#include <string.h>
int main() String = Indrajeet sinha, Address =
{ 355090448 String = Indrajeet sinha,
Address = 355090448
char *str; /* Initial memory allocation */
str = (char *) malloc(15);
strcpy(str, “Indra jeet Sinha");
printf("String = %s, Address = %u\n", str, str); /* Reallocating memory */
str = (char *) realloc(str, 25);
strcat(str, ".com");
printf("String = %s, Address = %u\n", str, str); /* Deallocate allocated memory */
free(str);
return(0);
47
}
ICE
3.3.1.4 REALLOC
Description
The C library function void *realloc(void *ptr, size_t
size)attempts to resize the memory block pointed to
by ptr that was previously allocated with a call
to malloc or calloc.
Declaration
void *realloc(void *ptr, size_t size)
Parameters
ptr -- This is the pointer to a memory block previously allocated
with malloc, calloc or realloc to be reallocated. If this is
NULL, a new block is allocated and a pointer to it is returned
by the function.
size -- This is the new size for the memory block, in bytes. If it
is 0 and ptr points to an existing block of memory, the
memory block pointed by ptr is deallocated and a NULL 48
pointer is returned.
ICE
Return Value
This function returns a pointer to the newly allocated memory, or
NULL if the request fails.
Example Output:
#include <stdio.h>
String = Indrajeet sinha, Address =
#include <stdlib.h>
355090448 String = Indrajeet sinha,
int main() { Address = 355090448
char *str; /* Initial memory allocation */
str = (char *)
malloc(15);
strcpy(str, “Indrajeet Sinha");
printf("String = %s, Address = %u\n", str, str); /* Reallocating memory */
str = (char *)
realloc(str, 25);
strcat(str, ".com");
printf("String = %s, Address = %u\n", str, str);
free(str); return(0); } 49