Monday, July 2, 2018

C : Use of fread()

Sample code:

The following example shows the usage of fread() function.

#include <stdio.h>
#include <string.h>

int main () {
   FILE *fp;
   char c[] = "this is tutorialspoint";
   char buffer[100];

   /* Open file for both reading and writing */
   fp = fopen("file.txt", "w+");

   /* Write data to the file */
   fwrite(c, strlen(c) + 1, 1, fp);

   /* Seek to the beginning of the file */
   fseek(fp, 0, SEEK_SET);

   /* Read and display data */
   fread(buffer, strlen(c)+1, 1, fp);
   printf("%s\n", buffer);
   fclose(fp);
   
   return(0);
}
 
 

fread() Function in C

The syntax of fread() function is this:
fread() function is the complementary of fwrite() function. fread() function is commonly used to read binary data. It accepts the same arguments as fwrite() function does.
Syntax: size_t fread(void *ptr, size_t size, size_t n, FILE *fp);

The ptr is the starting address of the memory block where data will be stored after reading from the file.
The function reads n items from the file where each item occupies the number of bytes specified in the second argument. On success, it reads n items from the file and returns n. On error or end of the file, it returns a number less than n.

Let's take some examples:
Example 1: Reading a float value from the file
int val;

fread(&val, sizeof(float), 1, fp);
This reads a float value from the file and stores it in the variable val.

Example 2: Reading an array from the file
int arr[10];

fread(arr, sizeof(arr), 1, fp);
This reads an array of 10 integers from the file and stores it in the variable arr.

Example 3: Reading the first 5 elements of an array
int arr[10];

fread(arr, sizeof(int), 5, fp);
This reads 5 integers from the file and stores it in the variable arr.

Example 4: Reading the structure variable
struct student
{
    char name[10];
    int roll;
    float marks;
};

struct student student_1;

fread(&student_1, sizeof(student_1), 1, fp);
This reads the contents of a structure variable from the file and stores it in the variable student_1.

Example 5: Reading an array of structure
struct student
{
    char name[10];
    int roll;
    float marks;
};

struct student arr_student[100];

fread(&arr_student, sizeof(struct student), 10, fp);
This reads first 10 elements of type struct student from the file and stores them in the variable arr_student.

The following program demonstrates how we can use fread() function.

#include<stdio.h>
#include<stdlib.h>

struct employee
{
    char name[50];
    char designation[50];
    int age;
    float salary
} emp;

int main()
{
    FILE *fp;
    fp = fopen("employee.txt", "rb");

    if(fp == NULL)
    {
        printf("Error opening file\n");
        exit(1);
    }

    printf("Testing fread() function: \n\n");

    while( fread(&emp, sizeof(emp), 1, fp) == 1 )
    {
        printf("Name: %s \n", emp.name);
        printf("Designation: %s \n", emp.designation);
        printf("Age: %d \n", emp.age);
        printf("Salary: %.2f \n\n", emp.salary);
    }

    fclose(fp);
    return 0;
}
Expected Output:
Testing fread() function:

Name: Bob
Designation: Manager
Age: 29
Salary: 34000.00

Name: Jake
Designation: Developer
Age: 34
Salary: 56000.00
 
How it works ?
In lines 4-10, a structure employee is declared along with a variable emp . The structure employee has four members namely: name, designation, age and salary.
In line 14, a structure pointer fp of type struct FILE is declared.
In line 15, fopen() function is called with two arguments namely "employee.txt" and "rb". On success, it returns a pointer to file employee.txt and opens the file employee.txt in read-only mode. On failure, it returns NULL.
In lines 17-21, if statement is used to test the value of fp. If it is NULL, printf() statement prints the error message and program terminates. Otherwise, the program continues with the statement following the if statement.
In lines 25-31, a while loop is used along with fread() to read the contents of the file. The fread() function reads the records stored in the file one by one and stores it in the structure variable emp. The fread() function will keep returning 1 until there are records in the file. As soon as the end of the file is encountered fread() will return a value less than 1 and the condition in the while loop become false and the control comes out of the while loop.
In line 33, fclose() function is used to close the file.


 

Sunday, July 1, 2018

HTML: INPUT types and attributes

Example code:

<html>
<head>
<meta charset="UTF-8">
<style>
        .blinking{
    animation:blinkingText 1.4s infinite;
    color:red;
}
@keyframes blinkingText{
    0%{     color: #000;    }
    49%{    color: red; }
    50%{    color: red; }
    99%{    color: red;  }
    100%{   color: #000;    }
}

</style>
</head>
<body bgcolor="dodgerblue">
<h2>The placeholder Attribute</h2>
<p>The placeholder attribute specifies a hint that describes the expected value of an input field (a sample value or a short description of the format).</p>

<form action="/action_page.php">
  <input type="text" name="fname" placeholder="First name"><br>
  <input type="text" name="lname" placeholder="Last name"><br>
  <input type="submit" value="Submit">
</form>
<marquee behavior="scroll" direction="right" scrollamount="1"><font color="green" size="20"><span class="blinking" >HTML</span></font></marquee>
<marquee behavior="scroll" direction="up"><font color="green" size="20" scrollamount="10"><span class="blinking" >Java</span></font></marquee>
<marquee behavior="scroll" direction="down"><font color="green" size="20"><span class="blinking" scrollamount="30">Python</span></font></marquee>
<p>
                <center> <select name="cars" size="3" multiple id="cars">
                  <option value="volvo">Volvo</option>
                    <option value="saab">Saab</option>
                        <option value="fiat">Fiat</option>
                    <option value="audi">Audi</option>
                    <option value="maruti">Maruti</option>
                    <option value="nano">Nano</option>
                </select>
                <input type="button" onclick="f1()" value="Values">
               
                <h2>The datalist Element</h2>
<p>The datalist element specifies a list of pre-defined options for an input element.</p>

<form name="f1" action="/">
 <input list="browsers" name="browser">
  <datalist id="browsers">
    <option value="Internet Explorer">
    <option value="Firefox">
    <option value="Chrome">
    <option value="Opera">
    <option value="Safari">
  </datalist>
  <input type="submit">
</form>

<form name="f2" action="/action_page.php">
  Select your favorite color:
  <input type="color" name="favcolor" value="#ff0000">
  <input type="submit">
</form>
The pattern Attribute

The pattern attribute specifies a regular expression that the <input> <br>element's value is checked against.

The pattern attribute works with the following input types: text, search, <br>url, tel, email, and password.
<form action="/action_page.php">
  Country code: <input type="text" name="country_code" pattern="[A-Z]{3}" title="Three letter country code">
  <input type="submit">
</form>
<h2>Email Field</h2>
<p>The <strong>input type="email"</strong> is used for input fields that should contain an e-mail address:</p>

<form name="f3" action="/action_page.php">

  E-mail:
  <input type="email" name="email" pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}$">
  <input type="submit">
</form>
<h2>Date Field Restrictions</h2>
<p>Use the min and max attributes to add restrictions to dates:</p>

<form  name="f4" action="/action_page.php">
Enter a date before 1980-01-01:<br>
<input type="date" name="bday" max="1979-12-31"><br><br>
Enter a date after 2000-01-01:<br>
<input type="date" name="bday" min="2000-01-02"><br><br>
<input type="submit">
</form>
<p>Depending on browser support:<br>A date picker can pop-up when you enter the input field.<p>

<form name="f5" action="/action_page.php">
  Birthday:
  <input type="date" name="bday">
  <input type="submit">
</form>
<p>Show a file-select field which allows a file to be chosen for upload:</p>
<h1>File upload</h1>
<form action="/action_page.php">
  Select a file: <input type="file" name="myFile"><br><br>
  <input type="submit">
</form>
<h2>Number Field</h2>
<p>The <strong>input type="number"</strong> defines a numeric input field.</p>
<p>You can use the min and max attributes to add numeric restrictions in the input field:</p>

<form action="/action_page.php">
  Quantity (between 1 and 5):
  <input type="number" name="quantity" min="1" max="5">
  <input type="submit">
</form>
 <form>
  Quantity:
  <input type="number" name="points" min="0" max="100" step="10" value="30">
  Text:
  <input type="text" value="Name" maxlength="8" size="10">
  Textarea:
  <input type="textarea" cols="20" rows="8" maxlength ="10">
 
</form>
 <form>
  <input type="range" name="points" min="0" max="10">
</form>
 <form>
  Search Google:
  <input type="search" name="googlesearch">
  <input type="submit">
</form>
<form action="/action_page.php">
  Telephone:
  <input type="tel" name="usrtel"> supported only by safari
  <input type="submit">
</form>
<h2>Time Field</h2>
<p>The <strong>input type="time"</strong> allows the user to select a time (no time zone):</p>

<p>Depending on browser support:<br>A time picker might pop-up when you enter the input field.</p>
<h2>Time:</h2>
<form action="/action_page.php">
  Select a time:
  <input type="time" name="usr_time">
  <input type="submit">
</form>
<h2>Week Field</h2>
<p>The <strong>input type="week"</strong> allows the user to select a week and year:</p>
<p>Depending on browser support:<br>A date picker can pop-up when you enter the input field.</p>

<form action="/action_page.php">
  Select a week:
  <input type="week" name="year_week">
  <input type="submit">
</form>
<h1>Input Attributes</h1>
<h2>The readonly Attribute</h2>
<p>The readonly attribute specifies that the input field is read only (cannot be changed):</p>

<form action="">
First name:<br>
<input type="text" name="firstname" value ="John" readonly>
<br>
Last name:<br>
<input type="text" name="lastname" autofocus>
Disabled atrr
First name:<br>
  <input type="text" name="firstname" value="John" disabled>
  When autocomplete is on, the browser automatically completes the input values based on values that the user has entered before.
   E-mail: <input type="email" name="email" autocomplete="off"><br>
</form>
The form Attribute

The form attribute specifies one or more forms an <input> element belongs to.
 <form action="/action_page.php" id="form1">
  First name: <input type="text" name="fname" required><br>
  <input type="submit" value="Submit">
</form>

Last name: <input type="text" name="lname" form="form1">
                </center>
<marquee behavior="alternate" scrollamount="40">Bouncing text...</marquee>
<marquee behavior="slide" direction="left">HTML slide-in text...</marquee>

<marquee behavior="scroll" direction="left" scrollamount="40"><font color="green" size="20"><span class="blinking" >C/C++</span></font></marquee>
</p>
<!-- <script src="myscripts.js"></script> External js file -->
<script>
function f1(){
    var v = document.getElementById("cars").value;
    alert(v);
}
</script>
</body>
</html>

JS:Get the value of checked checkbox/radio button?

Example code:

<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<h1>Get the value of checked checkbox?</h1>
<h2>Class name and name for one group should be same</h2>
<form action:"mailto:webwithjs@gmail.com" enctype="application/x-www-form-urlencoded" method = "post" autocomplete="on">
<br>checkbox<br>
<input class="messageCheckbox" type="checkbox" value="TV" id="tv" name="goods" checked>Television<br>
<input class="messageCheckbox" type="checkbox" value="Radio" id="radio" name="goods">Radio<br>
<br>Radio button<br>
<input  class="messageCheckbox"type ="radio" name="best" value="ahutosh" checked> Ashutosh<br>
<input class="messageCheckbox" type ="radio" name="best" value="kumar " > Kumar<br>
<input class="messageCheckbox" type ="radio" name="best" value="singh" > Singh<br>
<br>CheckBox<br>
<input class="messageCheckbox" type="checkbox" value="3" name="num">Three<br>
<input class="messageCheckbox" type="checkbox" value="1" name="num">One<br>
<center>

<input type="submit" value="Ship It"><input type="reset" value="Clear Entries">
<!--<button type="button" onclick="f1()" >press</button>-->
<input type ="button" onclick="f1()" value="press">
</center>

<script language="JavaScript">
function f1(){
var checkedValue = " ";
var inputElements = document.getElementsByClassName('messageCheckbox');
for(var i=0; inputElements[i]; ++i){
      if(inputElements[i].checked){
           checkedValue +=" "+inputElements[i].value;
           //break;
      }
}
alert(checkedValue);
}
</script>
</body>
</html>


JS: Arrays and Objects

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Arrays</h2>

<p>Arrays use numbers to access its elements.</p>

<p id="demo1"></p>

<p id="demo2"></p>

<script>
var person = ["Shiv in Array", "Doe", 46];      //array
document.getElementById("demo1").innerHTML = person[0];

var man = {firstName:"Ashutosh", lastName:"Doe in Object", age:46};   //object
document.getElementById("demo2").innerHTML = man["firstName"] + " "+man.lastName;  //TWO ways to access object properties
</script>

</body>
</html>

JS can Validate Input: Example

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Can Validate Input</h2>

<p>Please input a number between 1 and 10:</p>

<input id="numb">

<button type="button" onclick="myFunction()">Submit</button>

<p id="demo"></p>

<script>
function myFunction() {
    var x, text;

    // Get the value of the input field with id="numb"
    x = document.getElementById("numb").value;

    // If x is Not a Number or less than one or greater than 10
    if (isNaN(x) || x < 1 || x > 10) {
        text = "Input not valid";
    } else {
        text = "Input OK";
    }
    document.getElementById("demo").innerHTML = text;
}
</script>

</body>
</html>


HTML : frames

Example of Frames

<html>
    <head>
    <title>Frames</title>
    </head>
    <frameset cols="300,*,*">
        <frame src="splitString0.html">
        <frame src="formValidation.html">
    <frameset rows="50%,50%">
        <frame src="vb1.html">
        <frame src="DigitalClock.html" marginheight="100" marginwidth="79" scrolling=YES>
    </frameset>
    </frameset>
    <body>
    <noframes>your browser does not handles frames!</noframes>
    </body>
</html>


JS : Form Validtaion and DateTime formatting

This is an example :

<!DOCTYPE html>
<html>
<head>

<style>
body {background-color: lightgray;}
h2   {color: blue;}
p    {color: red;}
</style>



</head>
<body>
<fontcolor =magenta><h2 align=center >IGNOU Varanasi students Records</h2></font>
Today is  <span id = "t"></span>&nbsp;&nbsp;&nbsp; Time:  &nbsp;&nbsp;&nbsp; <span id="time">  </span> &nbsp;&nbsp;&nbsp; Date & Time: <span id="dtime"></span>
<br><hr>
<form name="myForm" action="/formValidation.html"
onsubmit="return validateForm()+ validateEmail(email)" method="post" id="myForm">
Name: <input type="text" name="fname">
<!--<input type="submit" value="Submit">-->
<hr><br><br>
Qualification: <input type="text" name="fqualification">
<hr><br><br>
Age : <input type="text" name="fage" required>
<hr><br><br>
Email: <input type="text" name="femail" id="email">
<span id="split"></span>

<p>Please input a number between 1 and 10:</p>

<input id="numb" name="fnumb">
<p id="demo"></p>
<p id="proceed"></p>
<hr>
<input type="button" onclick="myFunction()" value="Reset form">
<p id ="sub"><input type="submit" value="Submit" id="submit"></p>
</form>
<script>

/*
getFullYear() - Returns the 4-digit year
getMonth() - Returns a zero-based integer (0-11) representing the month of the year.
getDate() - Returns the day of the month (1-31).
getDay() - Returns the day of the week (0-6). 0 is Sunday, 6 is Saturday.
getHours() - Returns the hour of the day (0-23).
getMinutes() - Returns the minute (0-59).
getSeconds() - Returns the second (0-59).
getMilliseconds() - Returns the milliseconds (0-999).
getTimezoneOffset() - Returns the number of minutes between the machine local time and UTC.

*/
    var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
    var days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];

    var string = "Central University";
    var result = string.split(" ");
    var res='['+ '"'+result[0]+'"'+' "' + result[1]+ '"'+']';
    document.getElementById("split").innerHTML=res;
var email=document.getElementById("email").value;
var today=new Date();
//d = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate();
//var d= days[today.getDay()]+"  "+(today.getMonth()+1)+'-'+today.getDate()+'-'+today.getFullYear();
var min=today.getMinutes() ;
var sec=today.getSeconds() ;
if (min < 10) {
    min  = "0" + min;
}
if (sec < 10) {
    sec  = "0" + sec;
}
var hr = today.getHours();
var ampm = "am";
if( hr > 12 ) {
    hr -= 12;
    ampm = "pm";
}
if (hr < 10) {
    hr  = "0" + hr;
}
var d= days[today.getDay()]+"  "+(today.getMonth()+1)+'-'+today.getDate()+'-'+today.getFullYear();
//var time = today.getHours()+" AM " + ":" + today.getMinutes() + ":" + today.getSeconds();
//var time = today.getHours()+ ampm + ":" + today.getMinutes() + ":" + today.getSeconds();
var time = hr+" "+ ampm + " : " + min + " : " + sec;
var dateTime=d +'    '+time;
//var d =new Date();
//if (today.getMinutes() < 10) {
  //  today.getMinutes()  = "0" +today.getMinutes();
//}
document.getElementById("time").innerHTML = time;
document.getElementById("t").innerHTML = d;
document.getElementById("dtime").innerHTML = dateTime;
function myFunction() {
    document.getElementById("myForm").reset();
    }
function validateForm() {
    var x = document.forms["myForm"]["fname"].value;
    var y = document.forms["myForm"]["fqualification"].value;
    if(x==""||y==""){
        alert("Name and Qualification must be filled out");
        return false;
    }
    if (x == "") {
        alert("Name must be filled out");
        return false;
    }
    //var y = document.forms["myForm"]["fqualification"].value;
    if (y == "") {
        alert("Qualification must be filled out");
        return false;
    }
    var z=document.forms["myForm"]["fnumb"].value;
    if (z == "") {
        alert("Number must be filled out");
        return false;
    }
    if (isNaN(z) || z < 1 || z > 10) {
        text = "Input not valid";
        alert("Wrong Input not valid");
       
    } else {
        text = "All Inputs OK";
        document.getElementById("proceed").innerHTML="<input type=submit value=Proceed>";
        document.getElementById("sub").innerHTML="";
       
    }
    document.getElementById("demo").innerHTML = text;
   
   

}

function validateEmail(email){
    var reg = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
    if(reg.test(email)){
        return true;
    }
    else{
    alert('Please enter valid email.');
    return false;
    }
}
</script>

</body>
</html>

page:


Ampere's circuital law

  Ampere's circuital law states that the line integral of a magnetic field around any closed loop is equal to the permeability of free s...