JAYASHREE ORACLE CERTIFIED JAIN UNIVERSITY

Monday, October 11, 2010

DOWNLOAD PPT's ON POINTERS

http://uploading.com/files/get/f922ame4/

5th CHAPTER C-FILES NOTES

C Programming - File management in C

In this tutorial you will learn about C Programming - File management in C, File operation functions in C, Defining and opening a file, Closing a file, The getw and putw functions, The fprintf & fscanf functions, Random access to files and fseek function.

C supports a number of functions that have the ability to perform basic file operations, which include:
1. Naming a file
2. Opening a file
3. Reading from a file
4. Writing data into a file
5. Closing a file

  • Real life situations involve large volume of data and in such cases, the console oriented I/O operations pose two major problems
  • It becomes cumbersome and time consuming to handle large volumes of data through terminals.
  • The entire data is lost when either the program is terminated or computer is turned off therefore it is necessary to have more flexible approach where data can be stored on the disks and read whenever necessary, without destroying the data. This method employs the concept of files to store data.

File operation functions in C:

Function Name

Operation

fopen()

Creates a new file for use
Opens a new existing file for use

Fclose

Closes a file which has been opened for use

getc()

Reads a character from a file

putc()

Writes a character to a file

fprintf()

Writes a set of data values to a file

fscanf()

Reads a set of data values from a file

getw()

Reads a integer from a file

putw()

Writes an integer to the file

fseek()

Sets the position to a desired point in the file

ftell()

Gives the current position in the file

rewind()

Sets the position to the begining of the file

· Defining and opening a file:

If we want to store data in a file into the secondary memory, we must specify certain things about the file to the operating system. They include the fielname, data structure, purpose.

The general format of the function used for opening a file is

FILE *fp;
fp=fopen(“filename”,”mode”);

The first statement declares the variable fp as a pointer to the data type FILE. As stated earlier, File is a structure that is defined in the I/O Library. The second statement opens the file named filename and assigns an identifier to the FILE type pointer fp. This pointer, which contains all the information about the file, is subsequently used as a communication link between the system and the program.
The second statement also specifies the purpose of opening the file. The mode does this job.

R =>open the file for read only.

W =>open the file for writing only.


A =>open the file for appending data to it.

Consider the following statements:

FILE *p1, *p2;
p1=fopen(“data”,”r”);
p2=fopen(“results”,”w”);

In these statements the p1 and p2 are created and assigned to open the files data and results respectively the file data is opened for reading and result is opened for writing. In case the results file already exists, its contents are deleted and the files are opened as a new file. If data file does not exist error will occur.

Closing a file:

The input output library supports the function to close a file; it is in the following format.
fclose(file_pointer);

A file must be closed as soon as all operations on it have been completed. This would close the file associated with the file pointer.
Observe the following program.

….
FILE *p1 *p2;
p1=fopen (“Input”,”w”);
p2=fopen (“Output”,”r”);
….

fclose(p1);
fclose(p2)

The above program opens two files and closes them after all operations on them are completed, once a file is closed its file pointer can be reversed on other file.

The getc and putc functions are analogous to getchar and putchar functions and handle one character at a time. The putc function writes the character contained in character variable c to the file associated with the pointer fp1. ex putc(c,fp1); similarly getc function is used to read a character from a file that has been open in read mode. c=getc(fp2).

The program shown below displays use of a file operations. The data enter through the keyboard and the program writes it. Character by character, to the file input. The end of the data is indicated by entering an EOF character, which is control-z. the file input is closed at this signal.

#include<>
main()
{
file *f1;
printf(“Data input output”);
f1=fopen(“Input”,”w”); /*Open the file Input*/
while((c=getchar())!=EOF) /*get a character from key board*/
putc(c,f1); /*write a character to input*/
fclose(f1); /*close the file input*/
printf(“nData outputn”);
f1=fopen(“INPUT”,”r”); /*Reopen the file input*/
while((c=getc(f1))!=EOF)
printf(“%c”,c);
fclose(f1);
}

The getw and putw functions:

These are integer-oriented functions. They are similar to get c and putc functions and are used to read and write integer values. These functions would be usefull when we deal with only integer data. The general forms of getw and putw are:

putw(integer,fp);
getw(fp);

/*Example program for using getw and putw functions*/
#include<>
main()
{
FILE *f1,*f2,*f3;
int number I;
printf(“Contents of the data filenn”);
f1=fopen(“DATA”,”W”);
for(I=1;I< 30;I++)
{
scanf(“%d”,&number);
if(number==-1)
break;
putw(number,f1);
}
fclose(f1);
f1=fopen(“DATA”,”r”);
f2=fopen(“ODD”,”w”);
f3=fopen(“EVEN”,”w”);
while((number=getw(f1))!=EOF)/* Read from data file*/
{
if(number%2==0)
putw(number,f3);/*Write to even file*/
else
putw(number,f2);/*write to odd file*/
}
fclose(f1);
fclose(f2);
fclose(f3);
f2=fopen(“ODD”,”r”);
f3=fopen(“EVEN”,”r”);
printf(“nnContents of the odd filenn”);
while(number=getw(f2))!=EOF)
printf(“%d%d”,number);
printf(“nnContents of the even file”);
while(number=getw(f3))!=EOF)
printf(“%d”,number);
fclose(f2);
fclose(f3);
}

The fprintf & fscanf functions:

The fprintf and fscanf functions are identical to printf and scanf functions except that they work on files. The first argument of theses functions is a file pointer which specifies the file to be used. The general form of fprintf is

fprintf(fp,”control string”, list);

Where fp id a file pointer associated with a file that has been opened for writing. The control string is file output specifications list may include variable, constant and string.

fprintf(f1,%s%d%f”,name,age,7.5);

Here name is an array variable of type char and age is an int variable
The general format of fscanf is

fscanf(fp,”controlstring”,list);

This statement would cause the reading of items in the control string.

Example:

fscanf(f2,”5s%d”,item,&quantity”);

Like scanf, fscanf also returns the number of items that are successfully read.

/*Program to handle mixed data types*/
#include<>
main()
{
FILE *fp;
int num,qty,I;
float price,value;
char item[10],filename[10];
printf(“Input filename”);
scanf(“%s”,filename);
fp=fopen(filename,”w”);
printf(“Input inventory datann”0;
printf(“Item namem number price quantityn”);
for I=1;I< =3;I++)
{
fscanf(stdin,”%s%d%f%d”,item,&number,&price,&quality);
fprintf(fp,”%s%d%f%d”,itemnumber,price,quality);
}
fclose (fp);
fprintf(stdout,”nn”);
fp=fopen(filename,”r”);
printf(“Item name number price quantity value”);
for(I=1;I< =3;I++)
{
fscanf(fp,”%s%d%f%d”,item,&number,&prince,&quality);
value=price*quantity”);
fprintf(“stdout,”%s%d%f%d%dn”,item,number,price,quantity,value);
}
fclose(fp);
}

/*PART B:Program11:Create sequential file with three fieldempname,empname,empbasic Print All the details in a neat format by adding 500 to their basic salary.

#include<>
main()
{
FILE *fp;
int,empno,empbasic.i;
char empname[10];

fp=fopen(“empdatabase.txt”,”w”);

printf(“Input employee data”);
printf(“EMPNO EMPNAME EMPBASIC”);

for(i=1;i< =3;i++)
{
fscanf(stdin,”%d%s%d”,&empno,empname,&empbasic);
fprintf(fp,”%s%d%f%d%d”,empno,empname,empbasic,empbasic+500);
}

fclose (fp);
fp=fopen(“empdatabase.txt”,”r”);
printf(“EMPNO EMPNAME EMPBASIC”);

for(i=1;i< =3;i++)
{
fscanf(fp,”%d%s%d%d”,&empno,ename,&empbasic,empbasic+500);

fprintf(“stdout,”%d%s%d”,empno,empname,empbasic);
}
fclose(fp);

}

----------------------------------------------------------------------------------------------------------------

Random access to files:

Sometimes it is required to access only a particular part of the and not the complete file. This can be accomplished by using the following function:

1 > fseek

fseek function:

The general format of fseek function is a s follows:

fseek(file pointer,offset, position);

This function is used to move the file position to a desired location within the file. Fileptr
is a pointer to the file concerned. Offset is a number or variable of type long, and position in an integer number. Offset specifies the number of positions (bytes) to be moved from the location specified bt the position. The position can take the 3 values.

Value Meaning
0 Beginning of the file
1 Current position
2 End of the file.

PROGRAM ON SEQUENTIAL FILE

/*PART B:Program11:Create sequential file with three fieldempname,empname,empbasic Print All the details in a neat format by adding 500 to their basic salary.*/

#include<>
main()
{
FILE *fp;
int,empno,empbasic.i;
char empname[10];

fp=fopen(“empdatabase.txt”,”w”);

printf(“Input employee data”);
printf(“EMPNO EMPNAME EMPBASIC”);

for(i=1;i< =3;i++)
{
fscanf(stdin,”%d%s%d”,&empno,empname,&empbasic);
fprintf(fp,”%s%d%f%d%d”,empno,empname,empbasic,empbasic+500);
}

fclose (fp);
fp=fopen(“empdatabase.txt”,”r”);
printf(“EMPNO EMPNAME EMPBASIC”);

for(i=1;i< =3;i++)
{
fscanf(fp,”%d%s%d%d”,&empno,ename,&empbasic,empbasic+500);

fprintf(“stdout,”%d%s%d”,empno,empname,empbasic);
}
fclose(fp);

}

Friday, October 8, 2010

C PART B LAB PROGRAM

PART B
//Program 11:SEARCHING AN ELEMENT IN AN ARRAY USING POINTERS.

#include
#include
void main()
{
int a[100],i, s,n, flag=0;
int *p;

clrscr();
printf("\nEnter Number of elements in the array ");
scanf("%d",&n);

printf("\n Enter all the elements of the array\n\n");
for (i=0 ; i scanf("%d", &a[i]);

printf("\n\nEnter Search Element ");
scanf("%d", &s);

p=r;
for ( i=0; i < n ; i++)
{
if (*p == s)
{
flag=1;
break;
}
p++;
}

if (flag == 1)
printf("\nSerach element found") ;
else
printf("\nSerach Element Not found");

getch();
}
-----------------------------------------------------------------------
//program 12://CHECKING WHETHER THE GIVEN MATRIX IS AN IDENTITY MATRIX OR NOT
#include
#include
void main()
{
int a[10][10];
int i,j,r,c,flag=1;
clrscr();
printf("Enter the order of the Matrix ");
scanf("%d%d",&r,&c);
printf("Enter the elements of matrix ");
for(i=0;i {
for(j=0;j {
scanf("%d",&a[i][j]);
}
}

printf("Matrix A is \n");
for(i=0;i {
for(j=0;j {
printf("%3d",a[i][j]);
}
printf("\n");
}

/*Check for unit (or identity) matrix*/
for(i=0;i {
for(j=0;j {
if((i ==j ) & a[i][j] != 1 || ( i!=j) && (a[j][i] != 0 ))
{
flag=0;
break;
}
}
}
if(flag == 1)
printf("It is an identity matrix\n");
else
printf("It is not an identity matrix\n");
getch();
}

-------------------------------------------------------------------------------------

/*DECLARE 13 POINTER VARIABLES TO STORE A CHARACTER, A CHARACTER STRING AND AN INTEGER.DISPLAY THE ADDRESS AND

CONTENT OF EACH VARIABLE */
#include
#include
void main()
{
int a;
char b;
char c[10];
int *p;char *q,*r;

clrscr();
printf("\nEnter the integer value: ");
scanf("%d",&a);
p=&a;
fflush(stdin);

printf("\nEnter the character value: ");
b=getchar();
q=&b;
fflush(stdin);

printf("\nEnter the string: ");
gets(c);
r=c;

printf("\n\nThe address of %d = %u",a,p);
printf("\nThe content of %u = %d",p,*p);
printf("\n\nThe address of %c = %u",b,q);
printf("\nThe content of %u = %c",q,*q);
printf("\n\nThe address of %s= %u",c,r);

while(*r!='\0')
{
printf("\nThe content of %u = %c",r,*r);
++r;
}
getch();
}
---------------------------------------------------------------------------------------------------------
/*Program 14:Program to define a structure with three members and display the same*/

#include
#include

/* Structure Definition*/
struct book
{
char title[30];
char author[25];
float price;
int pages;
};

void main()
{
struct book book1;
clrscr();

/* Accepting Book Details*/
printf("Enter the title of the book: ");
gets(book1.title);
printf("Enter the Author of the book: ");
gets(book1.author);
printf("Enter the price of the book: ");
scanf("%f",&book1.price);
printf("Enter number of pages in the book: ");
scanf("%d",&book1.pages);

clrscr();
/* Displaying the Book Details*/
printf("Book Title: ");
printf("%s\n",book1.title);
printf("Author: ");
printf("%s\n",book1.author);
printf("Price: Rs.");
printf("%.2f\n",book1.price);
printf("Pages: ");
printf("%d",book1.pages);
getch();
}
--------------------------------------------------------------------------------------------
//Program 15:Program to declare a union with 3 members of type int,char&string
#include
#include
void main()
{

union student
{
int regno;
char section;
char name[20];
};

union student ns;

clrscr();
printf("\nEnter the student reg.no ");
scanf("%d",&ns.regno);
printf("\nEnter the student section ");
scanf("%s",&ns.section);
printf("\nEnter the name of student ");
scanf("%s",&ns.name);

printf("\n\n\nDetails of a student");
printf("\n------------------------\n");
printf("Size of union type variable is %d",sizeof(ns));
printf("\n\nThe value stored at the end is %s ",ns.name);
getch();

}
-------------------------------------------------------------------------------------
/* Program 16 :Sorting using Bubble Sort Method */
#include
#include
void main()
{
int array[10];
int i,j,n,temp;

clrscr();
printf("\n Sorting Using Bubble Sort Method \n\n");
printf("Enter Number of Elements: ");
scanf("%d",&n);

printf("\nEnter the elements one by one: ");
for(i=0;i {
scanf("%d",&array[i]);
}

/*Bubble sorting begins(ASCENDING ORDER)*/
for(i=0;i {
for(j=i+1;j {
if(array[i]>array[j])
{
temp=array[i];
array[i]=array[j];
array[j]=temp;
}
}
}

printf("\n\nsorted array in ASCENDING ORDER....\n");
for(i=0;i {
printf("%3d",array[i]);
}


printf("\n\nsorted array in DESCENDING ORDER....\n");
for(i=n-1;i>=0;i--)
{
printf("%3d",array[i]);
}
getch();
}
-----------------------------------------------------------------------
//Program 17: Addition and subtraction of two matrices.


#include
#include
void main()
{
int a[10][10],b[10][10],c[10][10],d[10][10],i,j,m,n,p,q;
clrscr();

printf("Enter the order of the matrix A\n");
scanf("%d%d",&m,&n);
printf("Enter the order of the matrix B\n");
scanf("%d%d",&p,&q);

if ((m==p)&&(n==q))
{
printf("Enter the elements of matrix A\n");
for(i=0;i for(j=0;j scanf("%d",&a[i][j]);

printf("Enter the elements of matrix B\n");
for(i=0;i for(j=0;j scanf("%3d",&b[i][j]);

printf("Matrix A\n");
for(i=0;i {
for(j=0;j {
printf("%3d",a[i][j]);
}
printf("\n");
}

printf("Matrix B\n");
for(i=0;i {
for(j=0;j {
printf("%3d",b[i][j]);
}
printf("\n");
}

for(i=0;i for(j=0;j c[i][j]=a[i][j]+b[i][j];

for(i=0;i for(j=0;j d[i][j]=a[i][j]-b[i][j];

printf("sum of matrices\n");
for(i=0;i {
for(j=0;j {
printf("%3d",c[i][j]);
}
printf("\n");
}

printf("Diference of matrices\n");
for(i=0;i {
for(j=0;j {
printf("%3d",d[i][j]);
}
printf("\n");
}
getch();
}
}
--------------------------------------------------------------------------------
//Program 18: Multiplication of two matrices.
#include
#include
void main()
{
int a[10][10],b[10][10],prod[10][10],i,j,k,n;
clrscr();

printf("\n Enter the order of matrix: ");
scanf("%d",&n);

printf("\n Enter the elements of matrix a: ");
for(i=0;i for(j=0;j scanf("%d",&a[i][j]);

printf(" Enter elements of Matrix b: ");
for(i=0;i for(j=0;j scanf("%d",&b[i][j]);

/*Compute product of matrix a & b */
for(i=0;i {
for(j=0;j {
prod[i][j]=0;
for(k=0;k prod[i][j]=prod[i][j] + a[i][k] * b[k][j];
}
}

printf("\n The product of a and b matrix \n");
for(i=0;i {
for(j=0;j {
printf("%4d",prod[i][j]);
}
printf("\n");
}

getch();
}
--------------------------------------------------------------------------
//Program 19: Check whether the given string is a palindrome or not.


-----------------------------------------------------------
//Program 20 Applying binary search to a set of N numbers by using a function.
//Binary search
#include
#include
void main()
{
int a[100];
int n,i,item,beg,end,mid;
clrscr();

printf("Enter no of elements");
scanf("%d",&n);

printf("\nEnter the elements");
for(i=0;i scanf("%d",&a[i]);

printf("Enter number to be searched");
scanf("%d",&item);
beg=0;
end=n-1;
mid=(beg + end) / 2;
if((beg<=end)&&(item!=a[mid]))
beg=mid+1;
else
end=mid-1;

mid=(beg+end)/2;
if ( a[mid]==item )
printf("\n %d is found in position %d",item,mid+1);
else
printf("\n Item does not exist");

}








C LAB PROGRAM PART A

/* 1.Program to print the reverse of an Interger */
#include
#include
void main()
{
long rev, n , num;
int r;
clrscr();
printf("\n\nProgram to print the reverse of an integer \n\n\n\n");
printf("Enter a Number ");
scanf("%ld",&num);
rev=0;
do
{
r = num %10;
num = num/10;
rev = rev*10 + r;
}
while (num >0);
printf("\n\nThe reverse is %ld ",rev);
getch();
}



---------------------------------------------------------------------

/* 2.Program to print the odd and even series of N Numbers */
#include
#include
void main()
{
int i,n;
clrscr();
printf("\n\n Program to print the odd and even series of No's\n\n\n\n");
printf("Enter the last Number ");
scanf("%d",&n);

printf("\n\nThe Odd Series\n\n");
for(i=1;i<=n; i++)
{
if(i%2==0)
printf("%3d",i);
else
printf("%3d",i);
}
getch();
}

----------------------------------------------------------------------
/*3:Get a string and convert the lowercase to uppercase and vice--versa using getchar() and putchar().


#include
#include
#include
void main()
{

char c;
while((c=getchar())!='\n')
{
c=toupper(c);
putchar(c);

getch(); }
}
----------------------------------------------------------------------
/* 4:Counting each vowels in string

#include
#include
#include

void main()
{
int a=0,e=0,i=0,o=0,u=0, c, length;
char str[100];
clrscr();

printf("\n\nProgram to get a string and find number of each of vowels appered in the string\n\n");
printf("Enter a String ");
gets(str);
length=strlen(str);

for(c=0;c switch (toupper (str[c]) )
{
case 'A':
a++;
break;
case 'E':
e++;
break;
case 'I':
i++;
break;
case 'O':
o++;
break;
case 'U':
u++;
break;
}

printf("\n\n There are %d a's \n" , a);
printf("\n\n There are %d e's \n" , e);
printf("\n\n There are %d i's \n" , i);
printf("\n\n There are %d o's \n" , o);
printf("\n\n There are %d u's \n" , u);
getch();
}
----------------------------------------------------------------------------------------------
/*
Program 5:Program to accept N words and make it as a sentence by inserting
blank spaces and a full stop at the end.
*/

#include
#include
#include

void main()
{

char str[10][20];
char sentence[200]="";
int n,i;
clrscr();
printf("\n\nProgram to accept N words and make it as a sentence by inserting blank spaces and a full stop at the end\n\n\n\n");
printf("\n Enter Number of words: ");
scanf("%d",&n);
for (i=0;i<=n; i++)
{
printf("Enter a String: ");
gets(str[i]);
if (i != n )
strcat(str[i]," ");
else
strcat(str[i], ".");

strcat(sentence,str[i]);
}
printf("\n\n%s", sentence);
getch();
}

------------------------------------------------------------------------------------------------
/*
Program 6:Program to print the reverse of a String
*/

#include
#include
#include

void main()
{

char str1[10], str2[10];
clrscr();
printf("\n\nProgram to print the reverse of a string \n\n");
printf("\nEnter a string: ");
scanf("%s",str1);
strcpy(str2,str1);
strrev(str2);
printf("\n\nThe reversed string is %s\n\n\n", str2);
if (strcmp(str1,str2) == 0)
printf("%s is a palindrome",str1);
else
printf("%s is not a palindrome",str1);
getch();
}
--------------------------------------------------------------------------------------
//Program 7:FINDING THE FIRST N TERMS OF FIBONACCI SERIES*/

#include
#include
void main()
{
int i,fib1=0,fib2=1,fib,n;
clrscr();

printf("\n How many Terms ? ");
scanf("%d",&n);

printf("\n %d \n %d",fib1,fib2);
for ( i=3;i <=n ; i++)
{
fib = fib1 + fib2;
printf("\n %d",fib);
fib1=fib2;
fib2=fib;
}

getch();
-------------------------------------------------------------------------------
//Program 8: Finding the maximum of 4 numbers by defining a macro for the maximum of two numbers.

#include
#include
#define MAX(n1,n2)((n1>n2)?n1:n2)
void main()
{
int a,b,c,d,t,lar;
clrscr();

printf("Input 4 nos : ");
scanf("%d%d%d%d",&a,&b,&c,&d);
t=MAX(a,b);
lar=MAX(MAX(t,c),d);

printf("\nLargest of %d, %d, %d, %d is %d",a,b,c,d,lar);
getch();

}


--------------------------------------------------------------------------------
//Program 9: Recursive program to find the factorial of an integer.

#include
#include
int fact(int);
void main()
{
int n;
clrscr();
printf("Enter any non-negative integer \n");
scanf("%d",&n);

if(n<0)
printf("invalid Input");
else
printf("Factorial of %d is = %d \n",n,fact(n));/*Function call*/
getch();
}

/*Recursive function to find the factorial of a number */
int fact(int n)
{
if(n==0)
return(1);
else
return(n*fact(n-1));
}
----------------------------------------------------------------------------
//Program 10:Demonstration of bitwise operations.
//Demonstration of bitwise operation.
#include
#include
void main()
{
int x,y,w=-1;
clrscr();

printf("Enter two integers: ");
scanf("%d%d",&x,&y);

printf("\n w= %d One's Compliment = ~w = %d \n",w,~w);
printf("\n x & y = %d \n",x & y);
printf("\n x | y = %d \n",x | y);
printf("\n x ^ y = %d \n",x ^ y);
printf("\n x << y = %d \n",x<<2);
printf("\n x >> y = %d \n",x>>2);

getch();
}