Difference between Spring and Struts framework



Spring is a light weight and open source framework created by Rod Johnson in 2003. Spring is a complete and a modular framework, Spring framework can be used for all layer implementations for a real time application or spring can be used for the development of particular layer of a real time application.

Struts is an open-source web application framework for developing Java EE web applications. It uses and extends the Java Servlet API to encourage developers to adopt a model–view–controller (MVC) architecture. It was originally created by Craig McClanahan and donated to the Apache Foundation in May, 2000.

Listed below is the comparison chart of difference between Spring and Strut Framework

Spring
Struts
Spring is a full-stack application framework that provides an MVC Framework
(Spring MVC) as one of its many modules.
Struts is a web framework which can be used to develop web applications using MVC pattern.

Spring Framework is said to be a non-invasive means it doesn’t force a programmer to extend or implement their class from any predefined class or interface given by Spring API
struts is said to be invasive .In struts we used to extend Action Class.
It forces the programmer that, the programmer class must extend from the base class provided by struts API
Spring implements IOC Design Pattern and addresses AOP Cross cutting concerns.
Struts implement MVC Design Patten
Spring is light weight framework
Struts is heavy weight framework
Spring is loosely coupled
Struts is tightly coupled
Spring is a Layered Architecture
Struts is a not a Layered Architecture
Spring provides easy integration with technologies like JDBC, Hibernate
We have to hard code to use technologies
like hibernate, jdbc, etc.
Spring framework not only allows JSPs but also
other views such as Velocity, Freemaker etc.
Struts allows only JSP as a view component.

Spring MVC provides more handler mappings.
Struts doesn’t have specific handler mappings but uses Action Mappings.
It also provides more model transfer.
It has fewer model transfer.
Spring offers complete Decoupling between layers in MVC.

Struts offers limited Decoupling between layers in MVC.

Spring offers IOC (inversion of control) and AOP (Aspect Oriented Programming).
Struts uses IOC internally but doesn’t provide to the programmer / developer.
Spring clear module division between Model, View and Controller.
Struts mixes Controller and Model.
Spring MVC just provides tags for basic HTML form tags
Struts 2 provides many out-of-box JSF-styled complex and composite tags
Such as: Ajax DOJO tags
Spring has spring webFlow for the same purpose, which is part of spring Framework.
Struts will be Generally used as a Front End Frame work.
Advantages of spring Framework:-
- Transaction management
- support for Messaging
- support and Integration with Other Frame works.
(Eg: Hibernate, Struts, Tapestry.. etc)
Advantages of Struts Framework:-
-Excellent support for Tag Library, which has wide industry acceptance.
-Easy to integrate with other client side technologies.


Difference between JDBC and Hibernate



JDBC stands for Java Database Connectivity allows developers to connect, query and update a database using the Structured Query Language. JDBC API standard provides Java developers to interact with different RDBMS and access table data through Java application without learning RDBMS details and using Database Specific JDBC Drivers.
Hibernate is an Object-Relational Mapping (ORM) solution for JAVA. It is a powerful, high performance object/relational persistence and query service. It allows us to develop persistent classes following object-oriented idiom – including association, inheritance and polymorphism.
Listed below is the comparison chart of difference beetween JDBC and Hibernate 

Hibernate 
JDBC 
Slower than JDBC and not used for Batch Processing.
Faster than Hibernate and used for Batch Processing.
Hibernate is Database Independent
JDBC query must be database specific
Criteria Query take care of Query Tuning.
JDBC you need to tune your queries.
Hibernate Supports two level of cache, you can store data into catch for better performance
in JDBC you need to implement your java cache.
Hibernate supports Query cache and It will provide the statistics about your query and database status.
JDBC Not provides any statistics.
No need to create any connection pool in case of Hibernate. You can use c3p0.
In JDBC you need to write your own connection pool
Hibernate Supports automatic versioning of rows
JDBC Not.
You can load your objects on start up using lazy=false in case of Hibernate.
JDBC Don't have such support.
In the xml file you can see all the relations between tables in case of Hibernate. Easy readability.
JDBC Not.
Hibernate is flexible and powerful ORM solution to map Java classes to database tables. Hibernate itself takes care of this mapping using XML files so developer does not need to write code for this.
With JDBC, developer has to write code to map an object model's data representation to a relational data model and its corresponding database schema.
Hibernate provides transparent persistence and developer does not need to write code explicitly to map database tables tuples to application objects during interaction with RDBMS.  
With JDBC, the automatic mapping of Java objects with database tables and vice versa conversion is to be taken care of by the developer manually with lines of code.  
Hibernate provides a powerful query language Hibernate Query Language (independent from type of database) that is expressed in a familiar SQL like syntax and includes full support for polymorphic queries. Hibernate also supports native SQL statements. It also selects an effective way to perform a database manipulation task for an application.  
JDBC supports only native Structured Query Language (SQL). Developer has to find out the efficient way to access database, i.e. to select effective query from a number of queries to perform same task.  
Hibernate provides this mapping itself. The actual mapping between tables and application objects is done in XML files. If there is change in Database or in any table then the only need to change XML file properties.  
Application using JDBC to handle persistent data (database tables) having database specific code in large amount. The code written to map table data to application objects and vice versa is actually to map table fields to object properties. As table changed or database changed then it’s essential to change object structure as well as to change code written to map table-to-object/object-to-table. 
Hibernate reduces lines of code by maintaining object-table mapping itself and returns result to application in form of Java objects. It relieves programmer from manual handling of persistent data, hence reducing the development time and maintenance cost.  
With JDBC, it is developer’s responsibility to handle JDBC result set and convert it to Java objects through code to use this persistent data in application. So with JDBC, mapping between Java objects and database tables is done manually.  
Hibernate, with Transparent Persistence, cache is set to application work space. Relational tuples are moved to this cache as a result of query. It improves performance if client application reads same data many times for same write. Automatic Transparent Persistence allows the developer to concentrate more on business logic rather than this application code.  
With JDBC, caching is maintained by hand-coding.  
Hibernate enables developer to define version type field to application, due to this defined field Hibernate updates version field of database table every time relational tuple is updated in form of Java class object to that table. So if two users retrieve same tuple and then modify it and one user save this modified tuple to database, version is automatically updated for this tuple by Hibernate. When other user tries to save updated tuple to database then it does not allow saving it because this user does not have updated data.  
In JDBC there is no check that always every user has updated data. This check has to be added by the developer.  

A List of SMTP, POP3 and IMAP Servers(Mail Server)


The following list of SMTP (Simple Mail Transfer Protocol), POP (Post Office Protocol) and IMAP ( Internet Message Access Protocol) server should help you if you don't know what mail server you should use for your mail account.

Default Ports:

    SMTP AUTH: Port 25 or 587 (some ISPs are blocking port 25)
    SMTP StartTLS Port 587
    SMTP SSL Port 465
    POP Port 110
    POP SSL Port 995
    IMAP Port 143
    IMAP SSL Port 993
    IMAP StartTLS Port 143

SMTP Server (Outgoing Messages) POP3 Server (Incoming Messages) IMAP Server (Incoming Messages)

Googlemail/Gmail SMTP POP3 Server/ IMAP Server
smtp.gmail.com
SSL Port 465
StartTLS Port 587
pop.gmail.com
SSL Port 995
Please make sure, that POP3 access is enabled in the account settings.
Login to your account and enable POP3.
imap.gmail.com
SSL Port 993
Please make sure, that IMAP access is enabled in the account settings.
Login to your account and enable IMAP.

Outlook.com SMTP POP3 Server
smtp.live.com
StartTLS Port 587
pop3.live.com
SSL Port 995
N/A
N/A

Yahoo Mail SMTP POP3 Server/ IMAP Server
smtp.mail.yahoo.com
SSL Port 465
pop.mail.yahoo.com
SSL Port 995
imap.mail.yahoo.com
SSL Port 993
Yahoo news server - news.yahoo.com

Yahoo Mail Plus SMTP POP3 Server / IMAP Server
plus.smtp.mail.yahoo.com
SSL Port 465
plus.pop.mail.yahoo.com
SSL Port 995
plus.imap.mail.yahoo.com
SSL Port 993

Hotmail SMTP / POP3 Server
smtp.live.com
StartTLS Port 587
pop3.live.com
SSL Port 995
N/A
N/A

AT&T SMTP POP3 Server / IMAP Server
smtp.att.yahoo.com
SSL Port 465
pop.att.yahoo.com
SSL Port 995
imap.att.yahoo.com
SSL Port 993

MSN SMTP POP3 Server / IMAP Server
smtp.email.msn.com
SSL Port: N/A
pop3.email.msn.com
SSL Port 110
N/A
N/A

AOL SMTP POP3 Server / IMAP Server
smtp.aol.com
Port: 587
N/A
N/A
imap.aol.com
143

Netscape SMTP POP3 Server / IMAP Server
smtp.isp.netscape.com
Port: N/A
pop3.isp.netscape.com
N/A
N/A
N/A
Netscape news server - news.netscape.com

Rediff SMTP POP3 Server / IMAP Server
smtp.rediffmailpro.com
Port: N/A
pop.rediffmailpro.com
N/A
N/A
N/A
Rediff news server - news.rediff.com

Note :- This list is without any warranties

Upload File using Servlet


To send an email using your a Servlet is simple enough but to start with you should have commons-fileupload.x.x.jar and commons-io-x.x.jar library files in your class path directory.

You Can download this files from You can download it from
commons-fileupload.x.x.jar ==>http://commons.apache.org/fileupload/
commons-io-x.x.jar ==> http://commons.apache.org/io/.

Upload.html

<html><head>
<title>File Uploading Form</title>
</head><body>
<h3>File Upload:</h3>
Select a file to upload: <br />
<form action="Upload" method="post" enctype="multipart/form-data">
<input type="file" name="file" size="50" /><br />
<input type="submit" value="Upload File" />
</form>
</body></html>

web.xml

Add following lines in web.xml. This would take care of accepting uploaded file and to store it in directory c:\uploaded\.

<context-param>
    <description>Location to store uploaded file</description>
    <param-name>file-upload</param-name>
    <param-value>c:\uploaded\</param-value>
</context-param>

Upload.Java

// Import required java libraries
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.output.*;

public class Upload extends HttpServlet {
  
   private boolean isMultipart;
   private String filePath;
   private int maxFileSize = 50 * 1024;
   private int maxMemSize = 4 * 1024;
   private File file ;

   public void init( ){
      // Get the file location where it would be stored.
      filePath =
             getServletContext().getInitParameter("file-upload");
   }
   public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException {
  // Check that we have a file upload request
  isMultipart = ServletFileUpload.isMultipartContent(request);
  response.setContentType("text/html");
  java.io.PrintWriter out = response.getWriter( );
  if( !isMultipart ){
     out.println("<html><head>");
     out.println("<title>Servlet upload</title>"); 
     out.println("</head><body>");
     out.println("<p>No file uploaded</p>");
     out.println("</body></html>");

     return;
  }
  DiskFileItemFactory factory = new DiskFileItemFactory();
  // maximum size that will be stored in memory
  factory.setSizeThreshold(maxMemSize);
  // Location to save data that is larger than maxMemSize.
  factory.setRepository(new File("c:\\temp"));

  // Create a new file upload handler
  ServletFileUpload upload = new ServletFileUpload(factory);
  // maximum file size to be uploaded.
  upload.setSizeMax( maxFileSize );
  try{
      // Parse the request to get file items.
      List fileItems = upload.parseRequest(request);
   
      // Process the uploaded file items
      Iterator i = fileItems.iterator();
      out.println("<html><head>");
      out.println("<title>Servlet upload</title>");
      out.println("</head><body>");

      while ( i.hasNext () )
      {
         FileItem fi = (FileItem)i.next();
         if ( !fi.isFormField () )   
         {
            // Get the uploaded file parameters
            String fieldName = fi.getFieldName();
            String fileName = fi.getName();
            String contentType = fi.getContentType();
            boolean isInMemory = fi.isInMemory();
            long sizeInBytes = fi.getSize();
            // Write the file
            if( fileName.lastIndexOf("\\") >= 0 ){
               file = new File( filePath +
               fileName.substring( fileName.lastIndexOf("\\"))) ;
            }else{
               file = new File( filePath +
               fileName.substring(fileName.lastIndexOf("\\")+1)) ;
            }
            fi.write( file ) ;
            out.println("Uploaded File: " + fileName + "<br>");
         }
      }
      out.println("</body>");
      out.println("</html>");
   } catch(Exception ex) { System.out.println(ex);  }
   }
}


Output

Upload.html
Upload Servlet

Kill process running on certain port in windows



"Starting of Tomcat failed, the server port 8080 is already in" or
"other process that is running on port 8080" or
"Port 8080 already in use"

Many new developers facing this error while they try to run a program on a local server.  this error occur because another instance is listening to same port but many users don’t know what is the process, and how to stop it from the Services manger in Windows.
here is a small tutorial to free up the particular port immediately.

we use following two DOS commands:-
1) Netstat
Displays protocol statistics and current TCP/IP network connections.
2) Taskkill
This command line tool can be used to end one or more processes. Processes can be killed by the process id or image name.

we use following code :-
C:\WINDOWS\system32>netstat -o -n -a | findstr 8080
  TCP    0.0.0.0:8080           0.0.0.0:0              LISTENING       4184


C:\WINDOWS\system32> taskkill /F /PID 4184
SUCCESS: Sent termination signal to the process with PID 4184.



Or We can kill any process from task manager also

Steps are as follows:
1)    Open Task manager
Press ALT + CTRL + DELETE
2)    Open “Processes” tab
3)    Click on “ View-> Select Columns ” Menu
4)    Click  check box  “PID- Process Identifier
this will show Process ID column which helps us in identifying running process
5)    Now Right Click on particular process
n click on End Process
Note:- Never kill system processes otherwise it results in immediate shutdown of windows.

To find more details about these commands use dos help utility “ /?”
Netstat /? Or Taskkill /?

Note:-  Sometimes we face error as
“  'netstat' is not recognized as an internal or external command, operable program or batch file.”
to use netstat command we have to relocate promt to “c:\windows\system32” folder
use following command

c:\> cd c:\windows\system32

Send email in servlet using gmail


To send an email using your a Servlet is simple enough but to start with you should have JavaMail API and Java Activation Framework (JAF) installed on your machine.
You need to add mail.jar and activation.jar files in your CLASSPATH.

Sending email

 We use the Java Mail API. In order to succeed sending an email, we must have a gmail account. We use the Google's smtp server to forward the email. So in the form, we must provide the login and the password of our gmail account. The example consists of five files. A css style file provides the look and feel for our jsp pages. The mail.html is used to fill in the form and send the data to the servlet. The EmailServlet processes the data and tries to send the email to the recipient. If it succeeds, the servlet forwards to the success.jsp file. If not, we receive an error message in error.jsp file.

style.css

body { width:1000px; border:0px; margin:0px auto; padding:0px; }
wrapper { margin:auto; width:1000px; }

.button { text-decoration:none; padding:8px; font:bold 12px Georgia,serif; color:white; 
background-color:rgb(0,130,130); border-color:rgb(0,130,130); }
.button:hover { text-decoration:none; padding:8px; font:bold 12px Georgia,serif; color:rgb(0,130,130);
background-color:white; border-color:rgb(0,130,130); }

fieldset { border-color:rgb(0,130,130); }
input:focus { background-color:yellow; }

mail.html

<html><head>
<title>Sending email</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head><body>

<div class="wrapper">
<fieldset style="padding:0px 10px 10px 10px; ">
<legend> Mail System </legend>

<form action="EmailServlet" method="post">  
<table> <tr> <td>From</td>
<td><input type="text" name="from"  size="60"></td>
</tr> <tr>
<td>To</td>
<td><input type="text" name="to"  size="60"></td>
</tr> <tr>
<td>Subject</td>
<td><input type="text" name="subject"  size="60"></td>
</tr> <tr>
<td>Message</td>
<td><textarea rows="10" cols="70" name="message"></textarea></td>
</tr> <tr>
<td>Login</td>
<td><input type="text" name="login" size="60"></td>
</tr> <tr>
<td>Password</td>
<td><input type="password" name="password" size="60"></td>
</tr> <tr>
<td><input type="submit" value="SUBMIT" class="button"></td>
<td><input type="reset" value="RESET" class="button"></td>
</tr> </table>
</form> </fieldset> </div>
</body> </html>

EmailServlet.java

import java.io.*;
import java.net.*;
import java.util.Properties;
import javax.mail.AuthenticationFailedException;
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.*;
import javax.servlet.http.*;

public class EmailServlet extends HttpServlet {

    protected void processRequest(HttpServletRequest request,
                                  HttpServletResponse response)
                   throws IOException, ServletException {
        final String err = "/error.jsp";
        final String succ = "/success.jsp";
        String from = request.getParameter("from");
        String to = request.getParameter("to");
        String subject = request.getParameter("subject");
        String message = request.getParameter("message");
        String login = request.getParameter("login");
        String password = request.getParameter("password");

        try {
            Properties props = new Properties();
            props.setProperty("mail.host", "smtp.gmail.com");
            props.setProperty("mail.smtp.port", "587");
            props.setProperty("mail.smtp.auth", "true");
            props.setProperty("mail.smtp.starttls.enable", "true");
            Authenticator auth = new SMTPAuthenticator(login, password);
            Session session = Session.getInstance(props, auth);
            MimeMessage msg = new MimeMessage(session);
            msg.setText(message);
            msg.setSubject(subject);
            msg.setFrom(new InternetAddress(from));
            msg.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
            Transport.send(msg);
        } 

            catch (AuthenticationFailedException ex) {
            request.setAttribute("ErrorMessage", "Authentication failed");
            RequestDispatcher dispatcher = request.getRequestDispatcher(err);
            dispatcher.forward(request, response);
        } 

            catch (AddressException ex) {
            request.setAttribute("ErrorMessage", "Wrong email address");
            RequestDispatcher dispatcher = request.getRequestDispatcher(err);
            dispatcher.forward(request, response);
        } 

            catch (MessagingException ex) {
            request.setAttribute("ErrorMessage", ex.getMessage());
            RequestDispatcher dispatcher = request.getRequestDispatcher(err);
            dispatcher.forward(request, response);
        }
            RequestDispatcher dispatcher = request.getRequestDispatcher(succ);
            dispatcher.forward(request, response);
    }
    private class SMTPAuthenticator extends Authenticator {
        private PasswordAuthentication authentication;
        public SMTPAuthenticator(String login, String password) {
            authentication = new PasswordAuthentication(login, password);
        }
        protected PasswordAuthentication getPasswordAuthentication() {
            return authentication;
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
                   throws ServletException, IOException {
        processRequest(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
                   throws ServletException, IOException {
        processRequest(request, response);
    }
}  


Error.jsp

<html> <head>
<title>Error</title>
<link rel="stylesheet" href="style.css" type="text/css">
</head>
<body> <center>
<div class="error">
<h2>Error</h2>
<p>Message: <%= request.getAttribute("ErrorMessage") %></p>
</div></center>
</body></html>

Success.jsp

<html><head>
<title>Message</title>
<link rel="stylesheet" href="style.css" type="text/css">
</head>  <body>
<center>
<div class="msg">
<h2>Message</h2>
<p> Email sent </p>
</div>    </center>
</body> </html>


Enjoy...............

GET HOST NAME & IP IN ORACLE 10G

Use the Oracle 10g utility “UTL_INADDR” to get the Local Host Name and IP of the machine your Oracle 10g is running on. You can do this by executing the following commands: 

BEGIN
DBMS_OUTPUT.PUT_LINE(UTL_INADDR.GET_HOST_NAME);
DBMS_OUTPUT.PUT_LINE(UTL_INADDR.GET_HOST_ADDRESS);
END;
/

Output :-

USER
192.168.1.16

PL/SQL procedure successfully completed.



Get current database name:-



for connected instance - 
SELECT ora_database_name FROM dual; 
OR
SELECT global_name FROM global_name;

OR
SELECT * FROM global_name;


Output :-

ORA_DATABASE_NAME
----------------------------------------------------------------
ORCL.REGRESS.RDBMS.DEV.US.ORACLE.COM


or
Get User name, Databse name, Terminal name and Session ID:-

select 'User: '|| user || ' on database ' || global_name, ' (term='||USERENV('TERMINAL')|| ', audsid='||USERENV('SESSIONID')||')' as MYCONTEXT from global_name;

thnks....

Show mouse position using javascript


Program to show Mouse Position using JavaScript.

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">

var IE = document.all?true:false
if(!IE)document.captureEvents(Event.MOUSEMOVE)
document.onmousemove = getMouseXY;

var tempX = 0
var tempY = 0

function getMouseXY(e)
{
    if (IE)
    {
        tempX = event.clientX + document.body.scrollLeft
        tempY = event.clientY + document.body.scrollTop
    }
    else
    { 
        tempX = e.pageX
        tempY = e.pageY
    } 

    document.Show.MouseX.value = tempX
    document.Show.MouseY.value = tempY

    return true
}
</script>    
</head>
<body>
<form name="Show">
      <input type="text" name="MouseX" value="0" size="4"> X<br>
      <input type="text" name="MouseY" value="0" size="4"> Y<br>
</form>
</body>
</html>


Add Favicon to site using Html



A Favicon is a graphic image associated with a particular Webpage and/or Website displayed by browser:
  • in the address box,
  • in the Favorites (Bookmarks) pane and menu,
  • modern browsers also display them in tabs,
  • and there is also an extension for Firefox, which displays favicons on Google search pages.
You can create a favicon in any icon editor. It should be 16×16 in size. Once you have the icon ready, rename it to favicon.ico and upload it to your Server root folder.


Assigning favicon to a page :- 

To activate your favicon, you must modify the source of your web page. Add this line to the <head> section of your page:

<link rel="shortcut icon" type="image/png" href="favicon.png" />
or
<link rel="shortcut icon" type="image/ico" href="favicon.ico" />

 Following example shows complete html of a very simple page with favicon:

<html>
<head>
<title>Title of my page</title>
<link rel="shortcut icon" type="image/png" href="favicon.png" />
</head>
<body>
Example to show use of Favicon.
</body>
</html>

Note: Simply changing the filename extension of an image to .ico without converting it to an ICO file will result in an error and not displaying the favicon.

Send data from html to jsp page



first.html

 <html>
<body>

<form action="second.jsp" method="post">

 Name :<input type="text" name="name">
 <input type="submit" value="SUBMIT">
</form>

</body>
</html>

User Input :- KK

****************************

Second.jsp

 <html>
<body>

Hi <%= request.getParameter("name") %>


</body>
</html>

Output:-

Hi KK

Applet code to move object

//Applet code to move object form left to right.

import java.awt.*;
import java.applet.*;
import java.lang.Thread;
import java.lang.*;

public class Applet1 extends Applet
{
Thread t;
int i;
int x=14,y=14;

        public void init()
        {
         t=new Thread();
        }
public void paint(Graphics g)
{
for(x=14;x<=getWidth();x=x+5)
        {
g.setColor(Color.BLACK);
g.fillRect(0,0,getWidth(),getHeight());
g.setColor(Color.RED);
g.fillOval(x,y,40,40);
repaint();
        try
{
t.sleep(50);
}
catch(Exception e)
{}
        }
        }
}

execution step:--

c:\javac Applet1.java

c:\appletviewer Applet1

C Program To Append Contents Into A File


#include< conio.h >
#include< stdio.h >
#include< process.h >
void main()
{
FILE *fp;
char c;
clrscr();
printf("Contents of the file =>\n");
fp=fopen("demo.txt","r");
while(!feof(fp))
{
c=fgetc(fp);
printf("%c",c);

 }
fp=fopen("demo.txt","a");
if(fp==NULL)
{
printf("file can't append\n");
exit(1);
}
printf("\nEnter the string to append\n");
while(c!='.')
{
c=getche();
fputc(c,fp);
}
fclose(fp);
printf("file contents after appending\n");
fp=fopen("demo.txt","r");
while(!feof(fp))
{
c=fgetc(fp);
printf("%c",c);
}
}

----------------------------------------------------------
OUT PUT:
----------------------------------------------------------
Contents of the file =>
This is c prorgam.

Enter the string to append
I upload C++ prorams soon.

File contents after appending
This is c prorgam.I upload C++ prorams soon.

C Program To Copy The Contents Of A One File To Another File


#include< stdio.h >
#include< conio.h >
#include< stdlib.h >
void main()
 {
FILE *fs,*ft;
char ch;
clrscr();
 fs = fopen("file1.txt","r");
 if(fs==NULL)
  {
 printf("Cannot open source file ! Press key to exit.");
 getch();
 exit(0);
  }
ft = fopen("file2.txt","w");
 if(ft==NULL)
{
printf("Cannot copy file !");
 fclose(fs);
 getch();
 exit(0);
 }
while(1)
 {
ch = getc(fs);
if(ch==EOF)
{
 break;
}
else
putc(ch,ft);
}
printf("File copied succesfully!");
fclose(fs);
fclose(ft);
}

----------------------------------------------------------
OUT PUT:
----------------------------------------------------------

File copied successfully!

C Program To Read And Write The Contents Into Of A File


#include< conio.h >
#include< stdio.h >
#include
void main()
{
FILE *fp;
char c;
clrscr();
fp=fopen("demo.txt","w");
if(fp==NULL)
{
printf("can't open file\n");
exit(1);

}
printf("write data and to stop press =>'.'\n");
while(c!='.')
{
c=getche();
fputc(c,fp);
}
fclose(fp);
printf("\n Read Data from File =>\n");
fp=fopen("demo.txt","r");
while(!feof(fp))
printf("%c",getc(fp));
getch();
}

----------------------------------------------------------
OUT PUT:
----------------------------------------------------------
Write data and to stop press => ’.’
C Programs.
 Read Data from File =>
C Programs.

implement C++ program for abstract classes

#include< iostream.h >
#include< conio.h >
class item
{                                                                                          
private:
int a,b,c,d;
public:
void get();
void multiply();
void sum();
};
void item::get()
{
cout<<"enter a & b :" ;
cin>>a>>b;
}
void item::sum()
{
c=a+b;
cout<<"\n sum is"<< c;
}
void item::multiply()
{
d=a*b;
cout<<"\n multiplication is "<< d;
}
void main()
{
clrscr();
item t;
t.get();
t.sum();
t.multiply();
getch();
}

-------------------------------------------------------
Out put
-------------------------------------------------------
Enter a & b : 5
4
Sum is 9
Multiplication is 20

implement C Program of towers of hanoi


Tower of hanoi is a historical problem, which can be easily expressed using recursion. There are N disks of decreasing size stacked on one needle, and two other empty needles. It is required to stack all the disks onto a second needle in the decreasing order of size. The third needle can be used as a temporary storage. The movement of the disks must confirm to the following rules,

1. Only one disk may be moved at a time
2. A disk can be moved from any needle to any other.
3. The larger disk should not rest upon a smaller one.

#include < stdio.h >
#include < conio.h >

void move ( int, char, char, char ) ;

void main( )
{
    int n = 3 ;
    clrscr( ) ;
    move ( n, 'A', 'B', 'C' ) ;
    getch( ) ;
}

void move ( int n, char sp, char ap, char ep )
{
    if ( n == 1 )
        printf ("\nMove from %c to %c ", sp, ep ) ;
    else
    {
        move ( n - 1, sp, ep, ap ) ;
        move ( 1, sp, ' ', ep ) ;
        move ( n - 1, ap, sp, ep ) ;
    }
}