0% found this document useful (0 votes)
2 views114 pages

Module-5 C Programming (1)

Module 5 covers pointers and file operations in C programming, including pointer declaration, initialization, and advantages. It explains how to access variables through pointers, perform operations on arrays using pointers, and includes various programming examples. Additionally, it discusses file handling functions and their applications in reading and writing data.

Uploaded by

reshmi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views114 pages

Module-5 C Programming (1)

Module 5 covers pointers and file operations in C programming, including pointer declaration, initialization, and advantages. It explains how to access variables through pointers, perform operations on arrays using pointers, and includes various programming examples. Additionally, it discusses file handling functions and their applications in reading and writing data.

Uploaded by

reshmi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 114

Module 5

Pointers, Files
2

syllabus
• Pointers and Files
• Basics of Pointer: declaring pointers, accessing data
though pointers, NULL pointer,array access using
pointers, pass by reference effect
• File Operations: open, close, read, write, append
Sequential access and random access to files: In built
file handlingfunctions (rewind() ,fseek(), ftell(), feof(),
fread(), fwrite()), simple programs covering pointers
and files.

Programming in C
Pointers
4

• Whenever we declare a variable, the system


allocates, somewhere in the memory, an appropriate
location to hold the value of the variable.
• Since, every byte has a unique address number, this
location will have its own address number.
• Consider the following statement:
int a=150

Programming in C
5

• Assume that the system has chosen the address


location 5000 for quantity.
• We may represent this as shown below.

Programming in C
6

Representation of a variable

• During execution of the program, the system always


associates the name “a” with the address 5000.
• To access the value 150 we use either the name
quantity or the address 5000.
• Since memory addresses are simply numbers, they
can be assigned to some variables which
can be stored in memory, like any other variable.
Such variables that hold memory addresses are
called pointers.

Programming in C
7

Pointer
• A pointer is a variable that contains an address
which is a location of another variable in memory.

Programming in C
8

Advantages of pointers
• Pointers provide direct access to memory
• Reduces the execution time of the program
• Provides an alternate way to access array elements
• Pointers can be used to pass information back and forth
between the calling function and called function.
• Pointers allows us to perform dynamic memory allocation and
deallocation.
• Pointers helps us to build complex data structures like linked
list, stack, queues, trees, graphs etc.
• Pointers allows us to resize the dynamically allocated memory
block.
• Addresses of objects can be extracted using pointers
Programming in C
9

Declaration of pointer variable


• The declaration of a pointer variable takes the
following form
datatype * pointer_name;
• Eg:
• int *p; //declares p as pointer variable that points
to an integer data type
• float *x; //declares p as pointer variable that points
to an floating point data type

Programming in C
10

Pointer declaration styles


• int* p; //style 1
• int *p; //style 2
• int * p; //style 2

• Style 2 is popular

Programming in C
11

• int *p;

•P
? ?
Contains garbage
Points to unknown
value
location

Programming in C
12

Initialization of pointer variable


• The process of assigning the address of a variable to
a pointer variable is known as initialization
• All un initialized pointers have some garbage value
so it should be initialized
• Eg:
int a;
int *p; //declaration
p=&a; //initialization

Programming in C
13

Example
int y = 5;
int *Ptr;
Ptr = &y; // Ptr gets address of y
//Ptr “points to” y

Programming in C
14

Can combine initialization with


declaration
int *p=&a; //valid

• Pointer variable should point to the corresponding type of data


For Eg:
1. float a,b;
int *p;
p=&a; //is wrong

2. int x,*p=&a; //is valid


(Declaration of data variable,pointer variable and initialization of
pointer variable in one step)

Programming in C
15

Accessing a variable through


its pointer
• A variable can be accessed through its pointer using
unary operator ’*’

• Also known as indirection operator or dereferencing


operator
• Eg:
int a=10;
int *p;
p=&a;
printf("value of a is%d \n",*p);
Programming in C
16

Example

#include<stdio.h>
void main()
{
int a=10;
int *p;
p=&a;
printf("value of a is%d \n",a);
printf("value of *p is %d \n",*p);
printf("value of p/address of a is %d \n ",p);
printf("value of p/address of a is %p \n ",p);
printf(“address of p is %d %p \n ",&p,&p);
}
Programming in C
17

Predict the output


Suppose
x stored at location 4104
#include<stdio.h> p stored at location 4106
void main() y stored at location 4108
{ %d in decimal
int x=10;
%p in hex
int *p;
p=&x;
int y=*p;
printf(" %d %p \n",x,&x); //output is 10 4104
printf(" %d %p \n",*&x,&x); //output is 10 4104
printf(" %d %p \n",*p,p); //output is 10 4104
printf(" %p %p \n",p,&p); //output is 4104 4106
printf(" %d %p \n",y,&y); //output is 10 4108
Programming in C
18

Program to find the sum of two


numbers using pointer
#include<stdio.h>
void main()
{
int x,y,sum,*xp,*yp;
printf("enter value of x");
scanf("%d",&x);
printf("enter value of y");
scanf("%d",&y);
xp=&x;
yp=&y;
sum=*xp+*yp;
printf(" sum is %d \n",sum);
} Programming in C
Program to find greatest of of two
numbers
#include<stdio.h>
void main()
{
int x,y,sum,*xp,*yp;
printf("enter value of x");
scanf("%d",&x);
printf("enter value of y");
scanf("%d",&y);
xp=&x;
yp=&y;
if(*xp>*yp)

printf(" %d is greater \n",*xp);


else
printf(" %d is greater \n",*yp);
}
Programming in C
20

Pgm to swap two variables


using pointers
#include<stdio.h>
void main()
{int x=10,y=20, temp,*a,*b;
printf(" before swapping");
printf(" value of x is %d \n",x);//output 10
printf(" value of y is %d \n",y);//output 20
a=&x;
b=&y;
temp= *a;
*a= *b;
*b=temp;
printf(" after swapping");
printf(" value of x is %d \n",x);//output 20
Programming in C
21

Reverse of a number using


pointers
#include<stdio.h>
void main()
{
int num,rev=0,digit,*ptr;
printf("enter number");
scanf("%d",&num);
ptr=&num;
while(*ptr !=0)
{
digit=*ptr %10;
rev=rev*10+digit;
*ptr=*ptr/10;

}
printf("reverse id %d",rev);
}

Programming in C
Pointer expressions (Predict the output) 22

#include<stdio.h>
void main()
{int x=10,y=20,sum,*m,*n,div;
m=&x;
n=&y;
sum=*m+*n;
printf(" sum is %d \n",sum);
//output is 30
x=*m+110;
printf(" value of x is %d \n",x);
//output is 120
div=*m/ *n;
printf(" div is %d \n",div);
//output is 6
div=*m /*n;
//is wrong,/* is considered as the begining of a comment
}

Programming in C
23

Pointer expressions
• c allow as to add and subtract integers from pointers
• When we increment a pointer its value is increased by the length of its data
type Suppose a is stored at location 3000
eg: P1 =3000
P2 =3004 (new compiler add 4byes for
#include<stdio.h> as single int var)
void main() printf("value of p1 is %d \n ",p1);
{ //output is 3000
int a=10; printf("value of p1+1 is %d \n ",p1+1);
int *p1; //output is 3004
p1=&a; printf("value of p1+2 is %d \n ",p1+2);
p2=p1+1; //output is 3008

printf("value of *p1 is %d \n",*p1); printf("value of p1+3 is %d \n ",p1+3);


//output is 3012
//output is 10
}

Programming in C
Predict the output
24

void main()

int *p , num;

p = &num;

*p = 100;

printf("%d\n" , num);

//output is 100

(*p)++;

printf("%d\n" , num);

//output is 101

(*p)--;

printf("%d\n" , num);

//output is 100

Programming in C
25

Null pointer- NULL


• A null pointer is a pointer which points nothing.
• Some uses of the null pointer are:
• To initialize a pointer variable when that pointer variable
isn’t assigned any valid memory address yet.
• To pass a null pointer to a function argument when we
don’t want to pass any valid memory address.
• To check for null pointer before accessing any pointer
variable. So that, we can perform error handling in pointer
related code e.g. dereference pointer variable only if it’s
not NULL.

Programming in C
26

#include <stdio.h>
int main()
{
int *i, *j;
int *ii = NULL, *jj = NULL;
if(i == j)
{
printf("This might get printed if both i and j are same by chance.");
}
if(ii == jj)
{
printf("This is always printed coz ii and jj are same.");
}
return 0;
}

Programming in C
27

Pointers and array

Programming in C
28

Pointer to an array
Consider an array:
int arr[4];

Programming in C
29

• In C programming, name of the array always points


to address of the first element of an array.
• In the above example, arr and &arr[0] points to the
address of the first element.
• &arr[0] is equivalent to arr

Programming in C
30

• Since, the addresses of both are the same, the values of arr and
&arr[0] are also the same.

• arr[0] is equivalent to *arr (value of an address of the pointer)


• Similarly,
• &arr[1] is equivalent to (arr + 1) AND, arr[1] is equivalent to *(arr + 1).
• &arr[2] is equivalent to (arr + 2) AND, arr[2] is equivalent to *(arr + 2).
• &arr[3] is equivalent to (arr + 3) AND, arr[3] is equivalent to *(arr + 3).
• .
• .
• &arr[i] is equivalent to (arr + i) AND, arr[i] is equivalent to *(arr + i).

Programming in C
31
• Given the declaration int a[3] = { 1, 2, 3 } ;
• int *aptr;
aptr=&a[0]; or
aptr=a;
aptr is a pointer to (the address of) a[0]
&a[0] is a pointer to a[0]
a[0] is the value 1
*aptr is also the value 1

&a[1] is a pointer to a[1]


(aptr + 1) is a pointer to a[1]

a[1] is the value 2


*(aptr + 1) is also the value 2

&a[2] is a pointer to a[2]


(aptr + 2) is a pointer to a[1]

a[2] is the value 2


*(aptr + 2) is also the value 2

Programming in C
32

• The generalized form for using pointer with an


array,
• *(a+i) is same as: a[i]

Programming in C
33

Pointers to Array Elements

• A pointer may be made to point to an element of an array by use


of the address operator:

int nums[ 10 ];
iptr = & nums[ 0 ];// iptr now points to zeroth element
Or
iptr=num;

iptr = & nums[ 3 ];// iptr now points to the fourth element

Programming in C
34

#include<stdio.h>
void main()
{

int a[10]={111,22,33,44},i,n;
//aptr=&a[0]; or

printf("printing address of first byte of the array in two ways %d %d\n ",a, &a[0]);
printf("print the value in first index using arrayname %d\n",*a);
printf("the address of second index in two ways %d %d\n",&a[1], a+1);

printf("print the value in second index using arrayname %d\n",*(a+1));


printf("the address of third index in two ways %d %d\n",&a[2], a+2);
//output is 111
//printf("%d",*(a+1));
//output is22
}

Programming in C
35

#include<stdio.h>
void main()
{

int a[10]={111,22,33,44},i,n,*aptr;
//aptr=&a[0]; or
aptr=a;
printf("%d",*aptr);

//output is 111
printf("%d",*(aptr+1));
//output is22
}

Programming in C
36

Pgm to read and print array using


pointers
#include<stdio.h> scanf("%d",(a+i));
void main() ///array pointer scanf("%d",
&a[i])
{
}
int a[10],i,n;
printf("enter limit");
scanf("%d",&n);
for(i=0;i<n;i++)
printf(“%d\n“, *(a+i)); //array
pointer printf("%d",a[i])
printf("enter
elements");
}
for(i=0;i<n;i++)
{
Programming in C
38

Pgm to find the sum of array elements


using pointers
#include<stdio.h> {
void main() scanf("%d",(aptr+i));
{ }
int
a[10],i,n,sum=0,*aptr; for(i=0;i<n;i++)
printf("enter limit"); {
scanf("%d",&n); sum=sum+*(aptr+i);
aptr=a; }
printf("enter printf("sum is %d",
elements"); sum );
for(i=0;i<n;i++) }

Programming in C
39

Pgm to Copy one array to another


using pointers
#include<stdio.h> for(i=0;i<n;i++)
void main() {
{ copy[i]=*(aptr+i);
int a[10],copy[10],i,n; }
int *aptr; printf("elements of copied
printf("enter limit"); array is");
for(i=0;i<n;i++)
scanf("%d",&n);
aptr=a; printf("%d ",copy[i]);

printf("enter elements");
}
for(i=0;i<n;i++)
scanf("%d",(aptr+i));

Programming in C
40

Pointers and Strings


• char str[6] = "Hello“

Creating a pointer for the string


• str holds the address of the first element of the
array i.e., it points at the starting memory address.
• char *ptr = str;

Programming in C
41

Programming in C
42

Using pointer to store string


• Pointer can also be used to create strings.
Pointer variables of char type are treated as
string.
• char *str = "Hello";
• This creates a string and stores its address in
the pointer variable str. The pointer str now
points to the first character of the string "Hello"

Programming in C
43

Predict the output if input is


“hello”
#include<stdio.h>
void main()
{
char name[100],*ptr;
printf("enter string");
scanf("%s",name); //input hello
ptr=name;
printf("%c",*ptr);
}
//output is h
Programming in C
44

Pgm to print the characters in a


string using pointers
#include<stdio.h>
void main()
{
char name[100],*ptr;
int i=0;
printf("enter string");
gets(name);
ptr=name;
while(*(ptr+i)!='\0') // same as while(name[i] != '\0')
{
printf(" %c",*(ptr+i));
i++;
}
Programming in C
45

Pgm to count the vowels in a


string using pointers(1)
#include<stdio.h>
void main()
{
char name[100],*ptr;
int i,vcount=0;
printf("enter string");
gets(name);
ptr=name;

Programming in C
46

Pgm to count the vowels in a


string using pointers(2)
while(*(ptr+i)!='\0')
{
if (* ptr+i =='a' || * ptr+i =='e'|| * ptr+i =='i'||* ptr+i =='o' ||* ptr+i =='u')
vcount++;
i++;

}
printf("vowel count is %d",vcount);
}

Programming in C
47

Pgm to count the words in a string


#include<stdio.h>
void main()
{
char name[100],*ptr;
int space=0;
printf("enter string");
gets(name);
ptr=name;
while(*ptr!='\0')
{
if (*ptr==' ')
space++;
ptr++;
}
printf("word count is %d",space+1);
}

Programming in C
48

Null pointer
• A null pointer is a pointer which points nothing.
• Some uses of the null pointer are:
• To initialize a pointer variable when that pointer
variable isn’t assigned any valid memory address
yet.
• To pass a null pointer to a function argument when
we don’t want to pass any valid memory address.
• To check for null pointer before accessing any
pointer variable. So that, we can perform error
handling in pointer related code e.g. dereference
pointer variable only if it’s not NULL.

Programming in C
49

#include <stdio.h>
int main()
{
int *i, *j;
int *ii = NULL, *jj = NULL;
if(i == j)
{
printf("This might get printed if both i and j are same by chance.");
}
if(ii == jj)
{
printf("This is always printed coz ii and jj are same.");
}
return 0;
}

Programming in C
50

Call by reference using pointer


void b(int *p)
Here the address of a is passed to the
{ function. So , the formal argument p stores
*p=20; the address of a. Thus any operation using
*p will affect the value of a.
}

void main()
{
int a=10;
b(&a);
printf("%d",a);
}
Programming in C
FILES
52

What is a File?
• A file is a collection of related data that a computers treats as
a single unit.
• Computers store files to secondary storage so that the
contents of files remain intact when a computer shuts down.
• When a computer reads a file, it copies the file from the
storage device to memory; when it writes to a file, it transfers
data from memory to the storage device.
• C uses a structure called FILE (defined in stdio.h) to store
the attributes of a file.

Programming in C
53

Types of Files

There are two types of files


1. Text files
2. Binary files

Programming in C
54

1. Text files
• Text files are the normal .txt files that you can easily create using
Notepad or any simple text editors.
• When you open those files, you'll see all the contents within the file as
plain text.
• You can easily edit or delete the contents.
• They take minimum effort to maintain, are easily readable, and provide
least security and takes bigger storage space.
2. Binary files
• Binary files are mostly the .bin files in your computer.
• Instead of storing data in plain text, they store it in the binary form
(0's and 1's).
• They can hold higher amount of data, are not readable easily and
provides a better security than text files.

Programming in C
Introduction
• Files are places where data can be stored permanently.
• Some programs expect the same set of data to be fed as
input every time it is run.
• Better if the data are kept in a file, and the program
reads from the file.
• Programs generating large volumes of output.
• Difficult to view on the screen.
• Better to store them in a file for later viewing/
processing

Programming in C
56

File Operations
• There are different operations that can be carried out on a file. These
are:
• Creation of a new file
• Opening an existing file
• Reading from a file
• Writing to a file
• Moving to a specific location in a file (seeking)
• Closing a file

Programming in C
Basic file operating functions 57

• fopen() -: creates and view a file or open an existing file


• fclose() -: used for closing the file
• getc() -: reads a character from the file
• putc() -: writes a character to the file
• getw() -: reads an integer from the file
• putw() -: writes an integer to the file
• fscanf() -: reads a set of data values from the file
• fprintf() -: writes a set of data values to the file
• fseek() -: set position to desired point in the file
• ftell() -: gives the current position in the file
• rewind()-: sets the position to beginning of the file

Programming in C
58

Programming in C
File Opening Modes 59

• Searches file. If the file is opened successfully fopen( ) loads it into


memory and sets up a pointer which points to the first character in it.
• "r“ If the file cannot be opened fopen( ) returns NULL.
• Operations possible – reading from the file.

• Searches file. If the file exists, its contents are overwritten. If the file
doesn’t exist, a new file is created.
• "w” • Returns NULL, if unable to open file.
• Operations possible – writing to the file.

• Searches file. If the file is opened successfully fopen( ) loads it into


memory and sets up a pointer that points to the last character in it. If
the file doesn’t exist, a new file is created. Returns NULL, if unable
• "a" to open file.
• Operations possible - adding new contents at the EOF

Programming in C
File Opening Modes 60

Searches file. If is opened successfully fopen( ) loads it into memory and


• “r+” sets up a pointer which points to the first character in it. Returns NULL, if
unable to open the file.
• Operations possible - reading existing contents, writing new contents,
modifying existing contents of the file.

• Searches file. If the file exists, its contents are overwritten. If the file
• "w+” 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.

• Searches file. If the file is opened successfully fopen( ) loads it into


memory and sets up a pointer which points to the first character in it. If
• "a+" the file doesn’t exist, a new file is created. Returns NULL, if unable to
open file.
• Operations possible - reading existing contents, appending new contents
to end of file. Cannot modify existing contents.
Programming in C
Opening a File
• A file must be “opened” before it can be used.
FILE *fp;
:
fp = fopen (filename, mode);
• fp is declared as a pointer to the data type FILE.(C has a
special "data type" for handling files which is defined in the
standard library 'stdio.h '.)
It is called the file pointer and has the syntax FILE*.
• filename is a string - specifies the name of the file.
• fopen returns a pointer to the file which is used in all
subsequent file operations.
• mode is a string which specifies the purpose of opening the
file:
“r” :: open the file for reading only
“w” :: open the file for writing only
“a” :: open the file for appending data to it

Programming in C
63

Facts about FILE Structure


• To perform any I/O operation on file, we need
FILE pointer.

FILE Structure is defined in stdio.h header file.

Programming in C
64

The fopen() function returns

• a pointer to a file structure if successful


• NULL if UNsuccessful

Programming in C
fopen( ) performs three important tasks 65

when you open the file in “r” mode

• Firstly it searches on the disk the file to be opened.


• Then it loads the file from the disk into a place in memory
called buffer.
• It sets up a character pointer that points to the first character
of the buffer.

Programming in C
66

Same argument also applies to writing information in a file. Instead of


writing characters in the file on the disk one character at a time it
would be more efficient to write characters in a buffer and then
finally transfer the contents from the buffer to the disk.

Programming in C
68

Closing a File
• After all operations on a file have been completed, it must be
closed.
• Ensures that all file data stored in memory buffers are properly
written to the file.
• fclose() function closes the file and returns zero on success,
or EOF if there is an error in closing the file.
• This EOF is a constant defined in the header file stdio.h.
• General format: fclose (file_pointer) ;
FILE *fp ;
fp= fopen (“test”, “w”) ;
…….
fclose (fp) ;

Programming in C
69

EOF(end of file)
• EOF macro which expands to an integer constant expression,
with type int and a negative value, that is returned by several
functions to indicate end-of-file, that is, no more input from a
stream.

• EOF is defined in stdio.h (and is usually -1).

• On linux, ctrl+d signals EOF, and on windows it's ctrl+z.

Programming in C
FILE INPUT/OUTPUT
71

getc(), putc() functions in C

• getc functions is used to read a character from a


file. In a C program, we read a character as below.
Eg: getc (fp);

• putc function is used to display a character on


standard output or is used to write into a file. In a C
program, we can use putc as below.

Eg:
putc(char, fp);
Programming in C
72

Getc ,putc eg:


pgm to read and print single character to a file

#include<stdio.h>
fp = fopen("test.txt", "r");
void main()
{
ch = getc(fp);
FILE *fp; printf("%c",ch);
char ch;
fp = fopen(“test.txt", "w"); fclose(fp);
printf("Enter character"); }
ch = getchar(); • //read the same char from
putc(ch,fp); the file, above the file is in
fclose(fp); write mode, cant read, close
it , then reopen it using read
mode
Programming in C
73

pgm to read and print many characters to a file


#include<stdio.h> putc(ch,fp);
void main()
{ }
FILE *fp; fclose(fp);
char ch; fp = fopen("one.txt", "r");
int limit,i; printf("The characters in the file
are");
printf("Enter limit");
scanf("%d",&limit); while((ch = getc(fp))!= EOF)

fp = fopen("one.txt", "w"); printf(" %c",ch);

printf("Enter characters");
for(i=0;i<limit;i++) fclose(fp);

{ ch=getchar(); }

Programming in C
75

getw and putw


• putw()
• putw function is used to write an integer into a
file.
• In a C program, we can write integer value in a
file as below.
putw(i, fp);
• where
i – integer value
fp – file pointer

Programming in C
76

getw and putw


• getw()
• getw function reads an integer value from a file
pointed by fp.
• In a C program, we can read integer value from
a file as below.
getw(fp);

Programming in C
77

#include<stdio.h>
fp = fopen("num.txt", "r");
main()
{
FILE *fp; n1 = getw(fp);
int n,n1; printf("%d",n1);
fp = fopen("num.txt", "w");
printf("Enter number");
scanf("%d",&n); fclose(fp);
putw(n,fp); }

fclose(fp);
Programming in C
78

Program to read and print n


numbers to a file
#include<stdio.h> putw(n,fp);
void main() }
{ fclose(fp);
FILE *fp; fp = fopen("num.txt", "r");
int n,n1,limit,i; printf("The numbers in the file
fp = fopen("num.txt", "w"); are");
printf("Enter limit"); while((n1 = getw(fp))!=EOF)
scanf("%d",&limit);
printf("Enter numbers"); printf(" %d",n1);
for(i=0;i<limit;i++)
{ fclose(fp);
scanf("%d",&n); }

Programming in C
79

Program to read an integers into file


and print even numbers from the file
#include<stdio.h> }
main() fclose(fp);
{ fp = fopen("num.txt", "r");
FILE *fp; while((n1 = getw(fp))!=EOF)
int n,n1,limit,i;
fp = fopen("num.txt", "w"); {
printf("Enter limit"); if(n1%2==0)
scanf("%d",&limit); printf(" %d",n1);
for(i=0;i<limit;i++)
{ }
scanf("%d",&n); fclose(fp);
putw(n,fp); }
Programming in C
Reading and Writing from File
using fprintf() and fscanf()
81

fprintf()
• The fprintf() function is used to write mixed type
in the file.
• Used to write characters, strings and integers in
one single file
• The fprintf() function is similar to printf() function
except the first argument which is a file pointer
that specifies the file to be written.
• The general form of fprintf is
• fprintf(fp,”control-string”,variable_list)

Programming in C
82

fscanf()
• The fscanf() function is used to read mixed type
form the file..
• Used to read characters, strings and integers in
one single file
• the fscanf() function is similar to scanf() function
except the first argument which is a file pointer
that specifies the file to be read.
• The general form of fprintf is
• fscanf(fp,”control-string”,variable_list)

Programming in C
83

Program to read and print name ,age


and gender of one person to a file
#include<stdio.h> printf("Enter gender");
void main() scanf("%c",&gender);
{ fprintf(fp,"%s %d
FILE *fp; %c",name,age,gender);
char name[10]; fclose(fp);
int age; fp = fopen("data.txt", "r");
char gender; fscanf(fp,"%s %d
%c",name,&age,&gender);
fp = fopen("data.txt", "w");
printf("Name is %s \n age is %d\n
printf("Enter name"); gender is %c \n
scanf("%s",name); ",name,age,gender);
printf("Enter age"); fclose(fp);
scanf("%d",&age); }
getchar();

Programming in C
Program to read and print name ,age 84

and gender of ‘n’ persons to a file


#include<stdio.h> scanf("%d",&age);
void main() getchar();
{ printf("Enter gender");
FILE *fp; scanf("%c",&gender);
char name[10]; fprintf(fp," %s %d %c",name,age,gender);
int age,limit,i; }
char gender; fclose(fp);
fp = fopen("datas.txt", "w"); fp = fopen("datas.txt", "r");
printf("enter limit"); printf("Name\tage\t gender-\n ");
scanf("%d",&limit); while((fscanf(fp,"%s %d
%c",name,&age,&gender))!=EOF)
for(i=0;i<limit;i++)
{
{

printf("%s\t%d\t%c\n ",name,age,gender);
printf("Enter name");
}
scanf("%s",name);
fclose(fp);
printf("Enter age");
Programming in C
Print the details of persons whose 85

gender is ‘f’
#include<stdio.h> scanf("%d",&age);
void main() getchar();
{ printf("Enter gender");
FILE *fp; scanf("%c",&gender);
char name[10]; fprintf(fp," %s %d %c",name,age,gender);
int age,limit,i; }
char gender; fclose(fp);
fp = fopen("datas.txt", "w"); fp = fopen("datas.txt", "r");
printf("enter limit"); printf("Name\tage\t gender-\n ");
scanf("%d",&limit); while((fscanf(fp,"%s %d
%c",name,&age,&gender))!=EOF)
for(i=0;i<limit;i++)
{
{
if(gender=='f')
printf("%s\t%d\t%c\n ",name,age,gender);
printf("Enter name");
}
scanf("%s",name);
fclose(fp);
printf("Enter age");
Programming in C
86

Program to read a string from


file and and print the vowels
#include<stdio.h> fp = fopen("vowel.txt", "r");
void main() while((ch=getc(fp))!=EOF)
{ {
FILE *fp; if (ch=='a' ||ch=='e'|| ch=='i'||
char str[10],ch; ch=='e'||ch=='o'|| ch=='u')

fp = fopen("vowel.txt", "w");
printf("Enter string"); putchar(ch);

scanf("%s",str);
fprintf(fp,"%s ",str); }

fclose(fp); fclose(fp);
}

Programming in C
87

Program to read a file rev.txt containing a


string. reverse the string and append the
reversed string in same file
#include<stdio.h> strrev(rev);
#include<string.h>
void main() printf("\nreversed string is %s",rev);
{
FILE *fp; fclose(fp);
int n,i,j=0; fp = fopen("rev.txt", "a");
char rev[10],ch; fprintf(fp," %s",rev);
fp = fopen("rev.txt", "r"); fclose(fp);
fscanf(fp,"%s",rev); }
printf("The string in the file is
%s",rev);

Programming in C
88

Random Access To File


(seeking)
There is no need to read each record
sequentially, if we want to access a particular
record.
C supports these functions for random access file
processing.

• fseek()
• ftell()
• rewind()

Programming in C
89

ftell()
• This function returns the value of the current pointer position in the file.
• The value is count from the beginning of the file.
• This function is useful in saving the current position of a file, which can be used later
in program
• Or in other words how many characters file pointer covered relative to starting
position
• Starting position is considered as 0

Syntax: ftell(fptr);

Where fptr is a file pointer.


• Eg:n=ftell(fptr) fptr
• n= 4
File position 0 1 2 3 4 5 6
H E L L
data

Programming in C
90

//persons records for(i=0;i<limit;i++)


#include<stdio.h>
void main() {
{
FILE *fp;
int age,limit,i;
printf("Enter age");
char gender; scanf("%d",&age);
fp = fopen("datas.txt", "w");
fprintf(fp,"%d",age);
printf("enter limit");
scanf("%d",&limit); printf("after writing %d\
printf("before 1st writing , after n",ftell(fp));
opening %d\n",ftell(fp));
}
} fclose(fp);
Programming in C
91

rewind()

• This function is used to move the file pointer to


the beginning of the given file.
• This function help us in reading a file more than
once, without having to close and open the file.
• When ever a file is opened for reading or writing
a rewind() is done implicitly
Syntax:
• rewind(fptr);
Where fptr is a file pointer.

Programming in C
92

Eg:

rewind( fptr);
n=ftell(fptr)
0 has the value 0 because the file position has
set to start of the file by rewind().
Note
First byte in the file is numbered 0 ,second as 1
and so on

Programming in C
93

rewind
#include<stdio.h> rewind(fp);
void main() printf("\nafter rewind %d\n",ftell(fp));
{
FILE *fp;
while((fscanf(fp,"%c",&c))!=EOF)
char name[10];
{
char c;
fp = fopen("rew.txt", "r"); printf("\n %c ",c);
printf(" before reading %d",ftell(fp)); printf(" CURRENT POS
while((fscanf(fp,"%c",&c))!=EOF) %d",ftell(fp));
{ }
fclose(fp);
printf("\n%c ",c);
printf(" CURRENT POS %d",ftell(fp));
}
}

Programming in C
94

fseek()

• This function is used to move the file position to a desired location


with in the file.
syntax:
fseek( file pointer, displacement, pointer position);
Where
file pointer ---- It is the pointer which points to the file.

displacement ---- It is positive or negative.


specifies number of bytes to be moved from location specified by
pointer position
This is the number of bytes which are skipped backward (if negative) or
forward( if positive) from the current position.

OPTIONAL- This is attached with L to make long integer in case of large text
file.

Programming in C
95

Pointer position:
This sets the pointer position in the file.
the Pointer position: can take one of the following
three values
0 Beginning of file.
1 Current position
2 End of file

Programming in C
96

• Ex:
• 1) fseek( fp,10L,0)

0 means pointer position is on beginning of the file,from this statement


pointer position is skipped 10 bytes from the beginning of the file.

2)fseek( fp,5L,1)

1 means current position of the pointer position.From this statement


pointer position is skipped 5 bytes forward from the current position.

3)fseek(fp,-5L,1)

From this statement pointer position is skipped 5 bytes backward from


the current position.

Programming in C
97

//ABCDEFGH fseek(fp,4L,0);
#include<stdio.h>
void main()
printf("\nafter fseek %d\
{
n",ftell(fp));
FILE *fp; fscanf(fp,"%c",&c);
char name[10];
printf("%c",c);
char c;
fp = fopen("rew.txt", "r");
printf(" before reading %d",ftell(fp));
fseek(fp,-3L,2);
while((fscanf(fp,"%c",&c))!=EOF)
{ printf("\nafter fseek %d\
n",ftell(fp));
printf("\n%c ",c); fscanf(fp,"%c",&c);
printf(" CURRENT POS %d",ftell(fp));
} printf("%c",c);

fseek(fp,0L,0);
fclose(fp);
printf("\nafter fseek %d\n",ftell(fp));
fscanf(fp,"%c",&c);
printf("%c",c); }
Programming in C
Operation of fseek function 98

• fseek(fp,0L,0); • Go to the beginning(rewind)


• fseek(fp,0L,1); • Stay at the current position (rare)
• fseek(fp,0L,2); • Go to EOF
• fseek(fp,m,0); • Move to (m+1)th byte in the file
• fseek(fp,m,1); • Go forward by m bytes from current
• fseek(fp,-m,1); position
• Go backward by m bytes from
current position

• Go backward by m bytes from the


• fseek(fp,-m,2); end

Programming in C
99

Types of data files


There are two different types of data files, called
1. stream-oriented (or standard access) data
files
2. system-oriented (or low-level) data files.
Stream oriented data files are generally easier to
work with and are therefore commonly used.
Stream-oriented data files can be subdivided into
two categories –
a) text files(formatted files)
b) unformatted data files.
Programming in C
100

text files(formatted files)


• Text files consist of consecutive characters.
• These characters can be interpreted as individual data items, or as
components of strings or numbers.
• Unformatted data files organizes data into blocks containing contiguous
bytes of information.
• These blocks represent more complex data structures, such as arrays and
structures.
• System-oriented data files are more closely related to the computer's
memory system than stream oriented data files.
• They are more complicated to work with, though their use may be more
efficient for certain kinds of applications.

Programming in C
101

UNFORMATTED DATA FILES


• Some applications involve the use of data files to store blocks
of data, where each block consists of a fixed number of
contiguous bytes.
• Each block will generally represent a complex data structure,
such as a structure or an array.
• For example, a data file may consist of multiple structures
having the same composition, or it may contain multiple arrays
of the same type and size.
• For such applications it may be desirable to read the entire
block from the data file, or write the entire block to the data
file, rather than reading or writing the individual components
(i.e. structure members or array elements) within each block
separately.

Programming in C
102

• The library function fread and fwrite are used in


this kind of situations.
• These functions are often referred to
as unformatted read and write functions.
• Similarly, data files of this type are often referred
to as unformatted data files.

Programming in C
103

The fwrite() function

• The fwrite() function is used to write records (sequence of bytes) to the file.
• A record may be an array or a structure.
• Syntax:

fwrite( ptr, int size, int n, FILE *fp );


The fwrite() function takes four arguments.

ptr : ptr is the reference of an array or a structure stored in memory.

size : size is the total number of bytes to be written.

n : n is number of times a record will be written.

fp : is the file pointer.

Programming in C
104

The fread() function


• The fread() function is used to read bytes form the file.
• This Function is Used in Binary Mode.

• Syntax of fread() function


• fread( ptr, int size, int n, FILE *fp );
• ptr : ptr is the reference of an array or a structure where data will
be stored after reading.
size : size is the total number of bytes to be read from file.
n : n is number of times a record will be read.
• fp: is the file pointer.

Programming in C
105

Program to insert an char array


into file
#include<stdio.h>

int main () {
FILE *fp;
char str[] = "saintgits colleg of engg";
char buffer[100];

fp = fopen( "file.txt" , "w" );


fwrite(str , 1 , sizeof(str) , fp );

fclose(fp);
fp = fopen( "file.txt" , "r" );
fread(buffer , 1 , sizeof(str) , fp );
printf("%s",buffer);
return(0);
}

Programming in C
106

Int array
#include<stdio.h>

int main () {
FILE *fp;
int a[]={10},b[1];
fp = fopen( "file.txt" , "w" );
fwrite(a , 2 , 2 , fp );

fclose(fp);
fp = fopen( "file.txt" , "r" );
fread(b , 2 ,2 , fp );
printf("%d",b[0]);
return(0);
}

Programming in C
107

Program to illustrate fread and


fwrite(1)(details of one person)
#include<stdio.h>

void main()
{
struct Student
{
int roll;
char name[25];
float marks;
};
FILE *fp;
char ch;
struct Student Stu;

Programming in C
108

Program to illustrate fread and


fwrite(2)
fp = fopen("Student","w");
printf("\nEnter Roll : ");
scanf("%d",&Stu.roll);
printf("Enter Name : ");
scanf("%s",Stu.name);
printf("Enter Marks : ");
scanf("%f",&Stu.marks);
fwrite(&Stu,sizeof(Stu),1,fp);
printf("\nData written successfully...");
fclose(fp);

Programming in C
109

Program to illustrate fread and


fwrite(3)

fp = fopen("Student","r");
printf("\n\tRoll\tName\tMarks\n");
fread(&Stu,sizeof(Stu),1,fp);
printf("\n\t%d\t%s\t
%f",Stu.roll,Stu.name,Stu.marks);
fclose(fp);
}

Programming in C
110

Details of n persons using fread


and fwrite(1)
#include<stdio.h> {
fp = fopen("Student.txt","r");
main() printf("\n\tRoll\tName\
printf("\nEnter Roll : ");
{
tMarks\n");
scanf("%d",&Stu[i].roll);
struct Student
{ printf("Enter Name : ");
int roll; scanf("%s",Stu[i].name); while(((fread(&Stu[i],sizeof(Stu[i]),1,f
p))>0))//!=EOF))
char name[25];
float marks; printf("Enter Marks : "); {
};
FILE *fp; scanf("%f",&Stu[i].marks);
char ch;
struct Student Stu[10]; fwrite(&Stu[i],sizeof(Stu[i]),1,fp); printf("\n\t%d\t%s\t
fp = %f",Stu[i].roll,Stu[i].name,Stu[i].mark
fopen("Student.txt","w"); s);
}
printf("\nData written }
int n,i;
successfully...");
printf("\nEnter limit ");
scanf("%d",&n); fclose(fp);
fclose(fp);
for(i=0;i<n;i++)
}

Programming in C
111

#include<stdio.h> fclose(fp);
fp=fopen(argv[1],"r");
while((ch=getc(fp))!=EOF)
void main(int argc, char* {
argv[]) if (ch=='a' ||ch=='e'|| ch=='i'|| ch=='e'||
{ ch=='o'|| ch=='u')
FILE * fp;
count++;
int count=0;
char ch,str[100]; }
fp = printf("%d",count);
fopen("vowelcount.txt", fclose(fp);
"w");
printf("Enter string");
scanf("%s",str); }
fprintf(fp,"%s ",str);

Programming in C
112

feof()
• tests the end-of-file indicator for the given
stream
• This function returns a True value when End-of-
File indicator associated with the stream is set,

Programming in C
113

//ABCDEFGH
#include<stdio.h>

void main () {
FILE *fp;
int c;

fp = fopen("rew.txt", "r");

while(!feof(fp))
{
c = fgetc(fp);
printf("%c", c);
}
fclose(fp);

} Programming in C
114

Nested stucutre
//nested struct
int main()
#include <stdio.h> {
#include <string.h> struct student_detail stu_data = {1, "Raju", 90.5,
71145,"Anna University"};
struct student_college_detail

{ printf(" Id is: %d \n", stu_data.id);


int college_id; printf(" Name is: %s \n", stu_data.name);
char college_name[50]; printf(" Percentage is: %f \n\n",
}; stu_data.percentage);

printf(" College Id is: %d \n",


struct student_detail
stu_data.clg_data.college_id);
{
printf(" College Name is: %s \n",
int id;
stu_data.clg_data.college_name);
char name[20];
return 0;
float percentage;
}
// structure within structure

struct student_college_detail clg_data;

};

Programming in C
115

Added topic
//write+ while(i<5)
{
#include <stdio.h>
scanf("%c",&ch);
#include <stdlib.h>
fputc(ch,fp);
int main() i++;
{ }
char ch,c; rewind(fp);
FILE *fp; printf("\nfrom file ");
while(!feof(fp))
int i=0;
{
fp = fopen("abcd.txt", "w+"); c = fgetc(fp);
printf("%c", c);
if(fp==NULL)
{ printf("no such file"); }
fclose(fp);
exit(0);
} return 0;
printf("Enter "); }

Programming in C
116

while(i<5)
{
//read+ scanf("%c",&ch);
#include <stdio.h> fputc(ch,fp);
#include <stdlib.h> i++;
int main()
}
{
rewind(fp);
char ch,c;
printf("\nfrom file ");
while(!feof(fp))
FILE *fp;
{
int i=0;
c = fgetc(fp);
fp = fopen("abc.txt", "r+");
printf("%c", c);
if(fp==NULL)
}
{ printf("no such file");
exit(0);//
fclose(fp);
}
//entering data into the file
return 0;
printf("Enter ");
}
Programming in C
117

END

Programming in C
118

Programming in C

You might also like