Module-5 C Programming (1)
Module-5 C Programming (1)
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
Programming in C
5
Programming in C
6
Representation of a variable
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
Programming in C
10
• Style 2 is popular
Programming in C
11
• int *p;
•P
? ?
Contains garbage
Points to unknown
value
location
Programming in C
12
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
Programming in C
15
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
}
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
Programming in C
Predict the output
24
void main()
int *p , num;
p = #
*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
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
Programming in C
28
Pointer to an array
Consider an array:
int arr[4];
Programming in C
29
Programming in C
30
• Since, the addresses of both are the same, the values of arr and
&arr[0] are also the same.
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
Programming in C
32
Programming in C
33
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);
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
Programming in C
39
printf("enter elements");
}
for(i=0;i<n;i++)
scanf("%d",(aptr+i));
Programming in C
40
Programming in C
41
Programming in C
42
Programming in C
43
Programming in C
46
}
printf("vowel count is %d",vcount);
}
Programming in C
47
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
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
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
Programming in C
58
Programming in C
File Opening Modes 59
• 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.
Programming in C
File Opening Modes 60
Programming in C
63
Programming in C
64
Programming in C
fopen( ) performs three important tasks 65
Programming in C
66
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.
Programming in C
FILE INPUT/OUTPUT
71
Eg:
putc(char, fp);
Programming in C
72
#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
printf("Enter characters");
for(i=0;i<limit;i++) fclose(fp);
{ ch=getchar(); }
Programming in C
75
Programming in C
76
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
Programming in C
79
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
Programming in C
Program to read and print name ,age 84
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
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
Programming in C
88
• 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);
Programming in C
90
rewind()
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()
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)
2)fseek( fp,5L,1)
3)fseek(fp,-5L,1)
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
Programming in C
99
Programming in C
101
Programming in C
102
Programming in C
103
• The fwrite() function is used to write records (sequence of bytes) to the file.
• A record may be an array or a structure.
• Syntax:
Programming in C
104
Programming in C
105
int main () {
FILE *fp;
char str[] = "saintgits colleg of engg";
char buffer[100];
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
void main()
{
struct Student
{
int roll;
char name[25];
float marks;
};
FILE *fp;
char ch;
struct Student Stu;
Programming in C
108
Programming in C
109
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
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
};
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