4.b) Write a function to count the number of
words present in a text file named“PARA.TXT”. Assume that each word is separated by a single blank/space character and no blanks/spaces in the beginning and end of the file.
Solution:
void WordsCount( )
{ clrscr( );
ifstream fin("PARA.TXT",ios::in);
char ch;
int Words=1;
if(!fin)
{ cout<<”No words at all in the file”;
exit(0);
}
while(fin)
{fin.get(ch);
if(ch= =’ ‘)
Words++;
}
cout<<"\nTotal number of Words in the file = "<<Words;
getch( );
}
4.c) Following is the structure of each recordin a data file named “PRODUCT.DAT” .
struct PRODUCT
{ char Product_Code[10] ;
char Product_Description[10] ;
int Stock ;
} ;
Write a function in C++ to update the file with a new value of Stock. The Stock and the Product_Code, whose Stock to be updated, are read during the execution of the program.
Solution:
void Update( )
{ fstream
finout(“PRODUCT.DAT”,ios::in|ios::out);
PRODUCT P;
finout.seekg(0);
while(finout) { finout.read((char *)&P, sizeof(P));
cout<<”\nThe Product Code is“<<P.Product_Code;
cout<<”\nThe Product Description is ”<<P.Product_Description;
cout<<”\nEnter the Stock: “;
cin>>P.Stock;
finout.seekp(finout.seekp( )- sizeof(P));
finout.write((char *)&P,sizeof(P));
}
}
CBSE Computer Science Solved Revision Tour By Mr. Ravi Kiran ( [email protected] )