Write a program which repeatedly reads numbers until the user enters “done”. Once “done” is entered, print out the total, count, and average of the numbers. If the user enters anything other than a number, detect their mistake using try and except and print an error message and skip to the next number.

Write a program which repeatedly reads numbers until the user enters “done”. Once “done” is entered, print out the total, count, and average of the numbers. If the user enters anything other than a number, detect their mistake using try and except and print an error message and skip to the next number.



'''
sum1=0
total=0
average=0
a=raw_input('Enter a number:')
while a!='done':
    try:
        a=float(a)
        sum1=sum1+a
        total=total+1
    except:
        print "Please insert a number"
    a=raw_input("Enter a number:")
print "Sum:",sum1
print "Total:",total
print "Average:",float(sum/total)

Write another program that prompts for a list of numbers as above and at the end prints out both the maximum and minimum of the numbers instead of the average.

Write another program that prompts for a list of numbers as above and at the end prints out both the maximum and minimum of the numbers instead of the average.




a=raw_input('Enter a number:')
min=a
max=a
while a!='done':
    try:
        a=float(a)
        if(float(a)>float(max)):
            max=a
        if(float(a)<float(min)):
            min=a
    except:
        print "Please insert a number"
    a=raw_input("Enter a number:")
print "Max:",max
print "Min:",min

How To Write a program in Python that asks user to input 5 lines of numbers. Your program should represent these lines as a table.

Write a program in Python that asks user to input 5 lines of numbers. Your program should represent these lines as a table.


#function that checks if n is float or not
def float_or_not(n):
    for char in n:
        if char == ".":
            return True

table = []

for i in range(5):
    numbers = input("Enter some numbers: ").split(" ")
    for x, y in enumerate(numbers):
        if float_or_not(y) == True:
            numbers[x] = float(y)
        else:
            numbers[x] = int(y)
    table.append(numbers)

print(table)

Write a function average() that takes no input but requests that the user enters a sentence, i.e. a string. Your function should return the average length of a word in the sentence.

Write a function average() that takes no input but requests that the user enters a sentence, i.e. a string. Your function should return the average length of a word in the sentence.


Usage:
>>> average()
Enter a sentence: Most modern calendars mar the sweet
simplicity of our lives by reminding us that each day
that passes is the anniversary of some perfectly
uninteresting event
5.115384615384615

So far I have this:

def average():
    wordCount = input('Enter a sentence: ')
    sum = 0
    if wordCount != 0:
        average = sum / wordCount
    else:
        average = 0
    return(average)

How to write a static python getitem method?

How to write a static python getitem method?



class A:
    @staticmethod
    def __getitem__(val):
        return "It works"

print A[0]

class MetaA(type):
    def __getitem__(cls,val):
        return "It works"

class A(object):
    __metaclass__=MetaA
    pass

print(A[0])
# It works

Write a function that reads the words in words.txt and stores them as keys in a dictionary. It doesn’t matter what the values are. Then you can use the in operator as a fast way to check whether a string is in the dictionary.

Write a function that reads the words in words.txt and stores them as keys in a dictionary. It doesn’t matter what the values are. Then you can use the in operator as a fast way to check whether a string is in the dictionary.



'''
f1=open('words.txt')
d1=dict()
i=0
for line in f1:
    words=line.split()
    for i in range(len(words)):
        d1[words[i]]=i
print d1
print 'abc' in d1

Write a class 'Example' that initializes two values 'v1' and 'v2' to '0' by default, and prints the values in this form: "Value 1: 20, Value 2: 30". When two objects of this class are added together using the '+' operator, the result is 'v1' of object 1 gets added to 'v1' of object 2 and 'v2' of object 1 gets added to 'v2' of object 2.

Write a class 'Example' that initializes two values 'v1' and 'v2' to '0' by default, and prints the values in this form: "Value 1: 20, Value 2: 30". When two objects of this class are added together using the '+' operator, the result is 'v1' of object 1 gets added to 'v1' of object 2 and 'v2' of object 1 gets added to 'v2' of object 2.


For example:
a = Example(20,30)
print(a)
Value 1: 20, Value 2: 30
b = Example(40,50)
c=a+b
print(c)
Value 1: 60, Value 2: 80



class Example(object):
  def __init__(self, v1 = 0, v2 = 0):
    self.v1 = v1
    self.v2 = v2
  def __add__(self, v1, v2):
    num = self.v1 + self.v2
    return num
 
def main():
  a = Example(20,30)
  print(a)
  b = Example(40,50)
  c=a+b
  print(c)
main()

Write a recursive Python function, given a non-negative integer N, to count and return the number of occurrences of the digit 7 in N.

Write a recursive Python function, given a non-negative integer N, to count and return the number of occurrences of the digit 7 in N.



For example:
count7(717) -> 2
count7(1237123) -> 1
count7(8989) -> 0


--------

def count7(N):
    Holder = N
    LastDigit = Holder % 10 #get the last digit using mod
    #if the last digit is 7 then add a tally and use the function again
    if LastDigit == 7:
        return (1 + count7(int(Holder/10))
    else:
        return (0 + count7(int(Holder/10))
   

count7(717)

Write a Python function that will take a the list of 100 random integers between 0 and 1000 and return the maximum value.

Write a Python function that will take a the list of 100 random integers between 0 and 1000 and return the maximum value. 

(Note: there is a builtin function named max but pretend you cannot use it.)


RUNSAVELOADSHOW CODELENS
"""
.comimport random

alist=[]
def listRandomFill(list):
    for i in range(100):
        list.append(random.randrange(0,1001))
    return(list)

def max(list):
    max=0
    for el in list:
        if max<el:
            max=el
    return max
print(max(listRandomFill(alist)))

Write a Python function named interleaveChars that is given two lines read from a text file, and returns a single string containing the characters of each string interleaved.

Write a Python function named interleaveChars that is given two lines read from a text file, and returns a single string containing the characters of each string interleaved.


def interleaveChars(name1, name2):

    ''' Returns a single string containing the characters of name1 and name2
        interleaved '''
       
    string = ''

    if len(name1) > len(name2):
        shortest = name2
        longest = name1
    else:
        shortest = name1
        longest = name2

    for i in range(len(shortest)):
        string = string + name1[i] + name2[i]
    string = string + longest[len(shortest):]
   
    return string

# main

input_file = open('P5_text.txt', 'r')

name1 = input_file.readline()[:-1]

while name1 != '':
    name2 = input_file.readline()[:-1]
    print(interleaveChars(name1, name2))
    name1 = input_file.readline()[:-1]

Write a Python class to find the three elements that sum to zero from a set of n real numbers.

Write a Python class to find the three elements that sum to zero from a set of n real numbers. 


Input array : [-25, -10, -7, -3, 2, 4, 8, 10]
Output : [[-10, 2, 8], [-7, -3, 10]]
"""


class Calculator(object):
    def do_work(self, my_array):
        pass

   
my_calc = Calculator()
my_calc.do_work([-25, -10, -7, -3, 2, 4, 8, 10])

assert(my_calc.do_work([-25, -10, -7, -3, 2, 4, 8, 10]) == [[-10, 2, 8], [-7, -3, 10]])
assert(my_calc.do_work([]) == [])

Write a function called general_poly, that meets the specifications below. For example, general_poly([1, 2, 3, 4])(10) should evaluate to 1234 because

Write a function called general_poly, that meets the specifications below. For example, general_poly([1, 2, 3, 4])(10) should evaluate to 1234 because


1 ∗ 10^3 + 2 ∗ 10^2 + 3 ∗ 10^1 + 4 ∗ 10^0.
"""

def general_poly(L):
    """
    L, a list of numbers (n0, n1, n2, ... nk)
    Returns a function, which when applied to a value x, returns the value
    n0 * x^k + n1 * x^(k-1) + ... nk * x^0
    """
    def helper(x):
        add = 0
        k = max(range(len(L)))#len(L)-1
        for i in L:#range(len(L)):
            add += i*x**k
            k -= 1
        return add
    return helper

Write a Python function that takes in two lists and calculates whether they are permutations of each other. The lists can contain both integers and strings.

Write a Python function that takes in two lists and calculates whether they are permutations of each other. The lists can contain both integers and strings. We define a permutation as follows:


the lists have the same number of elements
list elements appear the same number of times in both lists
If the lists are not permutations of each other, the function returns False.
If they are permutations of each other, the function returns a tuple consisting
of the following elements:

the element occuring the most times
how many times that element occurs
the type of the element that occurs the most times
If both lists are empty return the tuple (None, None, None). If more than one
element occurs the most number of times, you can return any of them.
"""


def is_list_permutation(L1, L2):
    '''
    L1 and L2: lists containing integers and strings
    Returns False if L1 and L2 are not permutations of each other.
            If they are permutations of each other, returns a
            tuple of 3 items in this order:
            the element occurring most, how many times it occurs, and its type
    '''
    if helper_permutation(L1,L2) == False:
        return False
    elif not L1:
        return (None, None, None)
    else:
        most = max(set(L1), key=L1.count) 
        num = L1.count(most)
        typ = type(most)
        return (most, num, typ)
   
def helper_permutation(L1,L2):
    if len(L1) != len(L2): # UNEQUAL LENGTH MEANS PERMUTATIONS OF EACH OTHER IS NOT POSSIBLE
        return False; 
    for i in range(0, len(L1)):
        if L1.count(L1[i]) != L2.count(L1[i]):
            return False

Write a Python function that takes in a string and prints out a version of this string that does not contain any vowels, according to the specification below. Vowels are uppercase and lowercase 'a', 'e', 'i', 'o', 'u'.

Write a Python function that takes in a string and prints out a version of this string that does not contain any vowels, according to the specification below. Vowels are uppercase and lowercase 'a', 'e', 'i', 'o', 'u'.


For example, if s = "This is great!" then print_without_vowels will print
Ths s grt!. If s = "a" then print_without_vowels will print the empty string .
"""

def print_without_vowels(s):
    '''
    s: the string to convert
    Finds a version of s without vowels and whose characters appear in the
    same order they appear in s. Prints this version of s.
    Does not return anything
    '''
    vowels = "aeiou"
    s1 = ""
    for i in s:
        if i not in vowels and i not in vowels.upper():
            s1 += i
    print(s1)
    return None

Write a function called dict_invert that takes in a dictionary with immutable values and returns the inverse of the dictionary. The inverse of a dictionary d is another dictionary whose keys are the unique dictionary values in d. The value for a key in the inverse dictionary is a sorted list (increasing order) of all keys in d that have the same value in d.

Write a function called dict_invert that takes in a dictionary with immutable values and returns the inverse of the dictionary. The inverse of a dictionary d is another dictionary whose keys are the unique dictionary values in d. The value for a key in the inverse dictionary is a sorted list (increasing order) of all keys in d that have the same value in d.


Here are two examples:

If d = {1:10, 2:20, 3:30} then dict_invert(d) returns {10: [1], 20: [2], 30: [3]}
If d = {1:10, 2:20, 3:30, 4:30} then dict_invert(d) returns {10: [1], 20: [2], 30: [3, 4]}
If d = {4:True, 2:True, 0:True} then dict_invert(d) returns {True: [0, 2, 4]}
"""

def dict_invert(d):
    '''
    d: dict
    Returns an inverted dictionary according to the instructions above
    '''
    result = {}
    for i in d:
        if d[i] not in result:
            result[d[i]] = []
        result[d[i]].append(i)
    return result

# GOT 18 OUT OF 20
"""
Test: dict_invert({8: 6, 2: 6, 4: 6, 6: 6})
Your output:
{6: [8, 2, 4, 6]}
Correct output:
{6: [2, 4, 6, 8]}
"""

Write a function is_triangular that meets the specification below. A triangular number is a number obtained by the continued summation of integers starting from 1. For example, 1, 1+2, 1+2+3, 1+2+3+4, etc., corresponding to 1, 3, 6, 10, etc., are triangular numbers.

Write a function is_triangular that meets the specification below. A triangular number is a number obtained by the continued summation of integers starting from 1. For example, 1, 1+2, 1+2+3, 1+2+3+4, etc., corresponding to 1, 3, 6, 10, etc., are triangular numbers.



"""

def is_triangular(k):

    """
    k, a positive integer
    returns True if k is triangular and False if not
    """
    mylist = []
    num = 0
    n = 2
    while n >= 2:
        num = sum(range(1,n))
        n += 1
        mylist.append(num)
        if num >= k:
            break
    return k in mylist

Write a python script that takes input.txt as input, parses it, and produces output.txt as output.

Write a python script that takes input.txt as input, parses it, and produces output.txt as output.


The script should be a general script that works on any file supplied with the format of input.txt.

The script should be run like this:

cat input.txt | python script.py > output.txt

[-- input.txt is below --]

* This is an outline

. It's not a very good outline

.. I've seen better

.. I've seen worse

... I saw a really bad one back in 2008

* This is the second numbered item in the outline

. This is sub text that spans multiple lines

This should be included with the previous line

And this line too

.. That is more sub text

* Numbers

. Some text

** Lots

. Some more text

. And some more

*** And lots

. One

.. Two

... Three

**** Of numbers

. Another line

** Less Numbers

. Text

*** More Numbers

. Blah

* One number again

. The last line

[-- output.txt is below this line --]

1 This is an outline
  + It's not a very good outline
   - I've seen better
   + I've seen worse
    - I saw a really bad one back in 2008
2 This is the second numbered item in the outline
  + This is sub text that spans multiple lines
    This should be included with the previous line
    And this line too
   - That is more sub text
3 Numbers
  - Some text
3.1 Lots
  - Some more text
  - And some more
3.1.1 And lots
  + One
   + Two
    - Three
3.1.1.1 Of numbers
  - Another line
3.2 Less Numbers
  - Text
3.2.1 More Numbers
  - Blah
4 One number again
  - The last line

Write a Python program that implements the ‘Shiritori" (first letter. last letter) game.

Write a Python program that implements the ‘Shiritori" (first letter. last letter) game. In this game, a person starts with a word. and the next person has to come up with a word that starts with the last letter of the previous word. (e.g.. If the first person starts with "apple", the next person has to come up with a word that starts with the letter ‘e'.)

Rules of the game:
1. Word must be a valid word.
2. Word must not have been used before.
3. Word must begin with the last letter of the previous word.

The Python program should take in an input word and check whether it exists in the database of words. If the word does not violate any rule of the game. it is deemed valid and the game continues. Else. the game ends.

The database of words would be the provided "word_list.txt" file. The program should open the "word_list.txt" file for reading, then read and store the contents of the file into a suitable Python data type.

The following illustrates what the game sessions might look like:

Please type a word: apple

Please type a word: egg

Please type a word: ear

You didn't type a word starting with '9'.
>>>

Please type a word: sun

Please type a word: new

Please type a word: won

Please type a word: new

You typed a word that has been typed before.
>>>

Please type a word: pear

Please type a word: rar

You didn't type a word found in word_list.txt.
>>>

Please make your code as clear and readable as possible. Comments to explain the workings of your code would be very much appreciated.

Write a Python program that encrypts or decrypts a given text into/from a secret language?

Write a Python program that encrypts or decrypts a given text into/from  a secret language?


Individual words in the text are encrypted according to the following rules:

If the word starts with a vowel append 'tan' to the word.  The vowels are a, e, i, o, u.
Otherwise, take the first letter of the word, move it to the end and then append 'est'.
So:

apple becomes appletan
orange becomes  orangetan
banana becomes ananabest
python becomes ythonpest
For simplicity we'll assume that the input text is in lowercase and that it does not contain any punctuation (no commas, periods, etc...)

Your program will first ask the user to make a choice between encryption into the secret language (E) or decryption from the secret language (D).

When the user specifies 'E' for encryption, the program will translate each word in the input text into the secret language, will put the translated words in reverse order into one translated message and will print out the translated message.  The translated message will have exactly one space character between words.

When the user specifies 'D' for decryption', the program will attempt to recover  the original words from the input text.  This is only possible if the words have a specific format:  they start with a vowel and end with tan or they end with a consonant followed by est.  If one or more word does not have this format, the decryption fails and the message 'Invalid Message' is printed.

Testing:
Make sure that you test your solution before you submit it.   Here are a few test cases with the expected output.  Feel free to add your own.

Test case 1 - encryption is correct for words starting with a vowel
Please type E to encrypt or D to decrypt a message: E
Please enter your message: apple
The secret message is: appletan

Test case 2 -  encryption is correct for words starting with a consonant (non vowel)
Please type E to encrypt or D to decrypt a message: E
Please enter your message: banana
The secret message is:  ananabest

Test case 3 - encryption is correct for phrases with multiple words
Please enter your message: python is fun
The secret message is: unfest istan ythonpest

Test case 4 - encryption is correct when words are separated by more than one space character
Please enter your message: simple     is better than complex
The secret message is: omplexcest hantest etterbest istan implesest

Test case 5 - decryption is correct for words ending with 'tan'
Please type E to encrypt or D to decrypt a message: D
Please enter your message: orangetan
The secret message is: orange

Test case 6 -  decryption is correct for words ending with a consonant followed with 'est'
Please type E to encrypt or D to decrypt a message: D
Please enter your message: ryptographycest
The secret message is: cryptography

Test case 7 - decryption is correct for phrases with multiple words
Please type E to encrypt or D to decrypt a message: D
Please enter your message: omplexcest hantest etterbest istan implesest
The secret message is: simple is better than complex

Test case 8 - The user is repeatedly prompted for input until they enter a valid choice (E or D)
Please type E to encrypt or D to decrypt a message: K
Invalid choice
Please type E to encrypt or D to decrypt a message: x
Invalid choice
Please type E to encrypt or D to decrypt a message: e
Invalid choice
Please type E to encrypt or D to decrypt a message: E
Please enter your message: hello
The secret message is: ellohest

Test case 9 - An invalid message is not decrypted
Please type E to encrypt or D to decrypt a message: D
Please enter your message: this is fun
Invalid Message

Write a Python program that prints the SHA256 hash of "Hello World" in hexadecimal.

Write a Python program that prints the SHA256 hash of "Hello World" in hexadecimal.


import hashlib
import codecs

def sha256(s):
    encoded = s.encode()
    hash_object = hashlib.sha256(encoded)
    print(hash_object.digest())
    return(hash_object.digest())

encoded_digest = sha256("Hello World")
print("Hexadecimal of SHA256 hashed message:", codecs.encode(encoded_digest, 'hex'))

# ```
# 21:14:28 › python3 hello_world.py
# b'\xa5\x91\xa6\xd4\x0b\xf4 @J\x01\x173\xcf\xb7\xb1\x90\xd6,e\xbf\x0b\xcd\xa3+W\xb2w\xd9\xad\x9f\x14n'
# Hexadecimal of SHA256 hashed message: b'a591a6d40bf420404a011733cfb7b190d62c65bf0bcda32b57b277d9ad9f146e'
# ```

Write a Python function that returns a list of keys in a Dict that map to integer values that are unique?

Write a Python function that returns a list of keys in a Dict that map to integer values that are unique (i.e. values appear exactly once in a Dict). The list of keys you return should be sorted in increasing order.
(If aDict does not contain any unique values, you should return an empty list.)

We are returning the key - not the value. We need to determine whether the key
relates to a value which is unique.

This function takes in a dictionary and returns a list.
"""
def uniqueValues(aDict):
    '''
    aDict: a dictionary
    '''
    sortList=[]
    outList=[]
    # Place values into a list
    #If there is only one of the values, then add to list. Otherwise, don't
    sortList = list(aDict.values())
    #need a loop to remove all instances of a duplicate
    #the length of the list will go down every time I remove an element
    #for i in range(len(sortList)):
    #    while sortList[i] in sortList[i+1:len(sortList)]:
    #        sortList.remove(sortList[i])
    #for i in range(len(sortList)):
    for i in sortList:
        if sortList.count(i) > 1: #if the item i appears in the list  > 1
            while i in sortList: #while that item is in the list
                sortList.remove(i) #remove that item!
   
    for k, v in aDict.items():
        if v in sortList:
            outList.append(k)
           
    outList.sort()
    return outList
   
testDict = {8: 3, 1: 3, 2: 2}
print(str(uniqueValues(testDict)))

How To convert a list of ASCII values to a string in python?

Use map instead of the list comprehension:


>>> L = [104, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100]
>>> ''.join(map(chr,L))
'hello, world'



def working_ascii(): """ G r e e t i n g s ! 71, 114, 101, 101, 116, 105, 110, 103, 115, 33 """

hello = [71, 114, 101, 101, 116, 105, 110, 103, 115, 33]
pmsg = ''.join(chr(i) for i in hello)
print(pmsg)

for i in range(33, 256):
    print(" ascii: {0} char: {1}".format(i, chr(i)))
working_ascii()



How To Create 2D Array using List in Python Programming?

How To Create 2D Array using List in Python Programming:


If for some reason you want to create a two dimensional array in Python and don't want to use external packages like numpy etc., the most obvious thing is to write a code like this :

>>> n = 3
>>> m = 4
>>> ara = [[0] * m] * n
>>> ara
[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]

But there is a problem. Check the code below-

>>> ara[0][0] = 1
>>> ara
[[1, 0, 0, 0], [1, 0, 0, 0], [1, 0, 0, 0]]
Actually, when you do [0] * m, it returns a reference to a list and when you multiply it with n, the same reference is duplicated. Hence you see the change in a way that you didn't expect.

The right way to do it is to append [0] * m, n times in the array. You can code it in multiple ways. My preferred way is:

>>> ara = [[0] * m for i in range(n)]

Python is an interpreted environment, What is the difference between interpreted and compiled environments.

Python is an interpreted environment, What is the difference between interpreted and compiled environments.



Interpreter: Fast to develop (edit and run). Slow to execute because each statement had to be interpreted into machine code every time it was executed (think of what this meant for a loop executed thousands of times). An interpreted language is one where the instructions are not directly executed by the the target machine, but instead read and executed by some other program (which normally is written in the language of the native machine). For example, the same "+" operation would be recognised by the interpreter at run time, which would then call its own "add(a,b)" function with the appropriate arguments, which would then execute the machine code "ADD" instruction.

Compiler: Slow to develop (edit, compile, link and run. The compile/link steps could take serious time). Fast to execute. The whole program was already in native machine code. A compiled language is one where the program, once compiled, is expressed in the instructions of the target machine. For example, an addition "+" operation in your source code could be translated directly to the "ADD" instruction in machine code.

C Program Arduino Wake Up Light

#include <Wire.h>
#include <RTClib.h>
#define ALR_HOUR 6
#define ALR_MIN 0
#define LCD_BACKLIGHT_TIME 3000L
#define FADE_EXTRA_TIME 600000L
#define RED_PIN 3
#define GREEN_PIN 5
#define BLUE_PIN 6
#define BUTTON_PIN 2
RTC_DS1307 RTC;
typedef struct {
  byte red;
  byte green;
  byte blue;
  unsigned int seconds;
} color_seq_item;
color_seq_item col0 = {  12,   1,    0,  300};
color_seq_item col1 = {  50,   1,    0,  300};
color_seq_item col2 = {  80,   10,   0,  300};
color_seq_item col3 = { 255,   60,   0,  180};
color_seq_item color_seq[] = {col0, col1, col2, col3};
int color_seq_size = sizeof(color_seq) / sizeof(color_seq_item);
void set_color(byte red, byte green, byte blue) {
  analogWrite(RED_PIN, red);
  analogWrite(GREEN_PIN, green);
  analogWrite(BLUE_PIN, blue);
}
void lcd_init() {
  Serial.write(0x7C);
  Serial.write(0x0D); // 9600 bauds
  delay(5);
  Serial.write(0x7C);
  Serial.write(0x04); // 16 char
  delay(5);
  Serial.write(0x7C);
  Serial.write(0x06); // 2 lines
  delay(5);
}
void lcd_clear() {
  Serial.write(0xFE);
  Serial.write(0x01);
  delay(5);
}
void lcd_back_on() {
  Serial.write(0x7C);
  Serial.write(157);
  delay(5);
}
void lcd_back_off(){
  Serial.write(0x7C);
  Serial.write(128);
  delay(5);
}
void update_lcd_time() {
  static enum {WAITING, UPDATING} state = WAITING;
  static unsigned long prev_millis = millis();
  DateTime time;
  switch(state) {
    case WAITING:
      if (millis() - prev_millis >= 1000) {
        prev_millis = millis();
        state = UPDATING;
      }
      break;
    case UPDATING:
      time = RTC.now();
      Serial.print("Hora: ");
      if (time.hour() < 10) Serial.print("0");
      Serial.print(time.hour());
      Serial.print(":");
      if (time.minute() < 10) Serial.print("0");
      Serial.print(time.minute());
      Serial.print(":");
      if (time.second() < 10) Serial.print("0");
      Serial.print(time.second());
      Serial.print("  ");
      Serial.print("Alarma: ");
      if (ALR_HOUR < 10) Serial.print("0");
      Serial.print(ALR_HOUR);
      Serial.print(":");
      if (ALR_MIN < 10) Serial.print("0");
      Serial.print(ALR_MIN);
      Serial.print("   ");
      state = WAITING;
      break;
  }
}
void update_lcd_backlight() {
  static enum {OFF, ON, DELAYING} state = OFF;
  static unsigned long prev_millis;
  switch(state) {
    case OFF:
      if (digitalRead(BUTTON_PIN) == LOW) {
        state = ON;
      }
      break;
    case ON:
      lcd_back_on();
      prev_millis = millis();
      state = DELAYING;
      break;
    case DELAYING:
      if (millis() - prev_millis >= LCD_BACKLIGHT_TIME) {
        lcd_back_off();
        state = OFF;
      }
      break;
  }
}
void update_wake_up() {
  static enum {WAITING, RUNNING, DELAYING, CANCELLED} state = WAITING;
  static unsigned long prev_millis = millis();
  static int seq_index;
  static int step_index;
  color_seq_item cur_item;
  color_seq_item next_item;
  unsigned long time_step_ms;
  int red, green, blue;
  DateTime time;

  switch(state) {
    case WAITING:
      if (millis() - prev_millis >= 1000) {
        prev_millis = millis();
        time = RTC.now();
      
        if ((time.hour() == ALR_HOUR) && (time.minute() == ALR_MIN) && (time.second() < 3)) {
          seq_index = 0;
          step_index = 0;
          state = RUNNING;
        }
      }
      break;
    case RUNNING:
      if (digitalRead(BUTTON_PIN) == LOW) {
        state = CANCELLED;
      } else {
        if (step_index == 256) {
          if (seq_index == (color_seq_size - 2)) {
            prev_millis = millis();
            state = DELAYING;
          } else {
            seq_index += 1;
            step_index = 0;
          }
        } else {
          cur_item = color_seq[seq_index];
          next_item = color_seq[seq_index + 1];
          time_step_ms = (cur_item.seconds * 1000UL) / 256UL;
        
          if (time_step_ms == 0) {
            set_color(cur_item.red, cur_item.green, cur_item.blue);
            step_index = 256;
          } else {
            if (millis() - prev_millis >= time_step_ms) {
              prev_millis = millis();
              red = ((cur_item.red * (255 - step_index)) + (next_item.red * step_index)) / 255;
              green = ((cur_item.green * (255 - step_index)) + (next_item.green * step_index)) / 255;
              blue = ((cur_item.blue * (255 - step_index)) + (next_item.blue * step_index)) / 255;
              set_color(red, green, blue);
              step_index += 1;
            }
          }
        }
      }
      break;
    case DELAYING:
      if (digitalRead(BUTTON_PIN) == LOW) {
        state = CANCELLED;
      } else {
        if (millis() - prev_millis >= FADE_EXTRA_TIME) {
          prev_millis = millis();
          set_color(0, 0, 0);
          state = WAITING;
        }
      }
      break;
    case CANCELLED:
      prev_millis = millis();
      set_color(0, 0, 0);
      state = WAITING;
      break;
  }
}
void setup() {
  Wire.begin();
  RTC.begin();
  pinMode(BUTTON_PIN, INPUT_PULLUP);
  Serial.begin(9600);
  lcd_init();
  lcd_clear();
  lcd_back_off();
  set_color(0, 0, 0);
  if (color_seq_size < 2) {
    while(1) {
      Serial.print("ERROR: color > 2");
      delay(1000);
    }
  }
}
void loop() {
  update_lcd_time();
  update_lcd_backlight();
  update_wake_up();
}

C Program To Copy The Contents Of One File Into Another Using fputc

#include<stdio.h>
#include<process.h>

void main()
{
FILE *fp1,*fp2;
char a;
clrscr();

fp1=fopen("test.txt","r");
if(fp1==NULL)
    {
    puts("cannot open this file");
    exit(1);
    }

fp2=fopen("test1.txt","w");
if(fp2==NULL)
    {
    puts("Not able to open this file");
    fclose(fp1);
    exit(1);
    }

   do
    {
    a=fgetc(fp1);
    fputc(a,fp2);
    }while(a!=EOF);

fcloseall();
getch();
}

Read first 50 char from 4 Scull_Dev using proc (edit main.c)

/*
 * main.c -- the bare scull char module
 *
 * Copyright (C) 2001 Alessandro Rubini and Jonathan Corbet
 * Copyright (C) 2001 O'Reilly & Associates
 *
 * The source code in this file can be freely used, adapted,
 * and redistributed in source or binary form, so long as an
 * acknowledgment appears in derived source files.  The citation
 * should list that the code comes from the book "Linux Device
 * Drivers" by Alessandro Rubini and Jonathan Corbet, published
 * by O'Reilly & Associates.   No warranty is attached;
 * we cannot take responsibility for errors or fitness for use.
 *
 */
#ifndef __KERNEL__
#  define __KERNEL__
#endif
#define SCULL_DEBUG
#ifndef MODULE
#  define MODULE
#endif
#include <linux/config.h>
#include <linux/module.h>
#include <linux/kernel.h>   /* printk() */
#include <linux/slab.h>   /* kmalloc() */
#include <linux/fs.h>       /* everything... */
#include <linux/errno.h>    /* error codes */
#include <linux/types.h>    /* size_t */
#include <linux/proc_fs.h>
#include <linux/fcntl.h>    /* O_ACCMODE */
#include <asm/system.h>     /* cli(), *_flags */
#include "scull.h"          /* local definitions */
#define SCULL_DEBUG
/*
 * I don't use static symbols here, because we export no symbols
 */
int scull_major =   SCULL_MAJOR;
int scull_nr_devs = SCULL_NR_DEVS;    /* number of bare scull devices */
int scull_quantum = SCULL_QUANTUM;
int scull_qset =    SCULL_QSET;
MODULE_PARM(scull_major,"i");
MODULE_PARM(scull_nr_devs,"i");
MODULE_PARM(scull_quantum,"i");
MODULE_PARM(scull_qset,"i");
MODULE_AUTHOR("Alessandro Rubini");
Scull_Dev *scull_devices; /* allocated in scull_init_module */
/*
 * Different minors behave differently, so let's use multiple fops
 */

struct file_operations *scull_fop_array[]={
    &scull_fops,      /* type 0 */
    &scull_priv_fops, /* type 1 */
    &scull_pipe_fops, /* type 2 */
    &scull_sngl_fops, /* type 3 */
    &scull_user_fops, /* type 4 */
    &scull_wusr_fops  /* type 5 */
};
#define SCULL_MAX_TYPE 5

int scull_trim(Scull_Dev *dev)
{
    Scull_Dev *next, *dptr;
    int qset = dev->qset;   /* "dev" is not-null */
    int i;
    for (dptr = dev; dptr; dptr = next) { /* all the list items */
        if (dptr->data) {
            for (i = 0; i < qset; i++)
                if (dptr->data[i])
                    kfree(dptr->data[i]);
            kfree(dptr->data);
            dptr->data=NULL;
        }
        next=dptr->next;
        if (dptr != dev) kfree(dptr); /* all of them but the first */
    }
    dev->size = 0;
    dev->quantum = scull_quantum;
    dev->qset = scull_qset;
    dev->next = NULL;
    return 0;
}
#ifdef SCULL_DEBUG /* use proc only if debugging */
/*
 * The proc filesystem: function to read and entry
 */
int scull_read_procmem(char *buf, char **start, off_t offset,
                   int count, int *eof, void *data)
{
    int i, j, len = 0;
    int limit = count - 80; /* Don't print more than this */
    for (i = 0; i < scull_nr_devs && len <= limit; i++) {
        Scull_Dev *d = &scull_devices[i];
        if (down_interruptible(&d->sem))
                return -ERESTARTSYS;
        len += sprintf(buf+len,"\nDevice %i: qset %i, q %i, sz %li\n",
                       i, d->qset, d->quantum, d->size);
        for (; d && len <= limit; d = d->next) { /* scan the list */
            len += sprintf(buf+len, "  item at %p, qset at %p\n", d, d->data);
            if (d->data && !d->next) /* dump only the last item - save space */
                for (j = 0; j < d->qset; j++) {
                    if (d->data[j])
                        len += sprintf(buf+len,"    % 4i: %8p\n",j,d->data[j]);
                }
        }
        up(&scull_devices[i].sem);
    }
    *eof = 1;
    return len;
}
int scull_read_50(char *buf, char **start, off_t offset,
                   int count, int *eof, void *data)
{
    int i, j, len = 0;
    int limit = count - 80; /* Don't print more than this */
    for (i = 0; i < scull_nr_devs && len <= limit; i++) {
        Scull_Dev *d = &scull_devices[i];
      
                for (j = 0; j < 50; j++) {
                  
                        len += sprintf(buf+len,"%c",(*((char*)d->data[0]+j)));
                }
        }
    
    }
    *eof = 1;
    return len;
}
#ifdef USE_PROC_REGISTER
static int scull_get_info(char *buf, char **start, off_t offset,
                int len, int unused)
{
    int eof = 0;
    return scull_read_procmem (buf, start, offset, len, &eof, NULL);
}
struct proc_dir_entry scull_proc_entry = {
        namelen:    8,
        name:       "scullmem",
        mode:       S_IFREG | S_IRUGO,
        nlink:      1,
        get_info:   scull_get_info,
};
static void scull_create_proc()
{
    proc_register_dynamic(&proc_root, &scull_proc_entry);
}
static void scull_remove_proc()
{
    proc_unregister(&proc_root, scull_proc_entry.low_ino);
}
#else  /* no USE_PROC_REGISTER - modern world */
static void scull_create_proc()
{
    create_proc_read_entry("scullmem", 0 /* default mode */,
                           NULL /* parent dir */, scull_read_procmem,
                           NULL /* client data */);
create_proc_read_entry("scull50", 0 /* default mode */,
                           NULL /* parent dir */, scull_read_50,
                           NULL /* client data */);
}
static void scull_remove_proc()
{
    /* no problem if it was not registered */
    remove_proc_entry("scullmem", NULL /* parent dir */);
}

#endif /* USE_PROC_REGISTER */




#endif /* SCULL_DEBUG */




/*
 * Open and close
 */

/* In scull_open, the fop_array is used according to TYPE(dev) */
int scull_open(struct inode *inode, struct file *filp)
{
    Scull_Dev *dev; /* device information */
    int num = NUM(inode->i_rdev);
    int type = TYPE(inode->i_rdev);
    /*
     * the type and num values are only valid if we are not using devfs.
     * However, since we use them to retrieve the device pointer, we
     * don't need them with devfs as filp->private_data is already
     * initialized
     */
    /*
     * If private data is not valid, we are not using devfs
     * so use the type (from minor nr.) to select a new f_op
     */
    if (!filp->private_data && type) {
        if (type > SCULL_MAX_TYPE) return -ENODEV;
        filp->f_op = scull_fop_array[type];
        return filp->f_op->open(inode, filp); /* dispatch to specific open */
    }
    /* type 0, check the device number (unless private_data valid) */
    dev = (Scull_Dev *)filp->private_data;
    if (!dev) {
        if (num >= scull_nr_devs) return -ENODEV;
        dev = &scull_devices[num];
        filp->private_data = dev; /* for other methods */
    }
    MOD_INC_USE_COUNT;  /* Before we maybe sleep */
    /* now trim to 0 the length of the device if open was write-only */
    if ( (filp->f_flags & O_ACCMODE) == O_WRONLY) {
        if (down_interruptible(&dev->sem)) {
            MOD_DEC_USE_COUNT;
            return -ERESTARTSYS;
        }
        scull_trim(dev); /* ignore errors */
        up(&dev->sem);
    }
    return 0;          /* success */
}
int scull_release(struct inode *inode, struct file *filp)
{
    MOD_DEC_USE_COUNT;
    return 0;
}
/*
 * Follow the list
 */
Scull_Dev *scull_follow(Scull_Dev *dev, int n)
{
    while (n--) {
        if (!dev->next) {
            dev->next = kmalloc(sizeof(Scull_Dev), GFP_KERNEL);
            memset(dev->next, 0, sizeof(Scull_Dev));
        }
        dev = dev->next;
        continue;
    }
    return dev;
}
/*
 * Data management: read and write
 */
ssize_t scull_read(struct file *filp, char *buf, size_t count,
                loff_t *f_pos)
{
    Scull_Dev *dev = filp->private_data; /* the first listitem */
    Scull_Dev *dptr;
    int quantum = dev->quantum;
    int qset = dev->qset;
    int itemsize = quantum * qset; /* how many bytes in the listitem */
    int item, s_pos, q_pos, rest;
    ssize_t ret = 0;
    if (down_interruptible(&dev->sem))
            return -ERESTARTSYS;
    if (*f_pos >= dev->size)
        goto out;
    if (*f_pos + count > dev->size)
        count = dev->size - *f_pos;
    /* find listitem, qset index, and offset in the quantum */
    item = (long)*f_pos / itemsize;
    rest = (long)*f_pos % itemsize;
    s_pos = rest / quantum; q_pos = rest % quantum;
    /* follow the list up to the right position (defined elsewhere) */
    dptr = scull_follow(dev, item);
    if (!dptr->data)
        goto out; /* don't fill holes */
    if (!dptr->data[s_pos])
        goto out;
    /* read only up to the end of this quantum */
    if (count > quantum - q_pos)
        count = quantum - q_pos;
    if (copy_to_user(buf, dptr->data[s_pos]+q_pos, count)) {
        ret = -EFAULT;
 goto out;
    }
    *f_pos += count;
    ret = count;
 out:
    up(&dev->sem);
    return ret;
}
ssize_t scull_write(struct file *filp, const char *buf, size_t count,
                loff_t *f_pos)
{
    Scull_Dev *dev = filp->private_data;
    Scull_Dev *dptr;
    int quantum = dev->quantum;
    int qset = dev->qset;
    int itemsize = quantum * qset;
    int item, s_pos, q_pos, rest;
    ssize_t ret = -ENOMEM; /* value used in "goto out" statements */
    if (down_interruptible(&dev->sem))
            return -ERESTARTSYS;
    /* find listitem, qset index and offset in the quantum */
    item = (long)*f_pos / itemsize;
    rest = (long)*f_pos % itemsize;
    s_pos = rest / quantum; q_pos = rest % quantum;
    /* follow the list up to the right position */
    dptr = scull_follow(dev, item);
    if (!dptr->data) {
        dptr->data = kmalloc(qset * sizeof(char *), GFP_KERNEL);
        if (!dptr->data)
            goto out;
        memset(dptr->data, 0, qset * sizeof(char *));
    }
    if (!dptr->data[s_pos]) {
        dptr->data[s_pos] = kmalloc(quantum, GFP_KERNEL);
        if (!dptr->data[s_pos])
            goto out;
    }
    /* write only up to the end of this quantum */
    if (count > quantum - q_pos)
        count = quantum - q_pos;
    if (copy_from_user(dptr->data[s_pos]+q_pos, buf, count)) {
        ret = -EFAULT;
 goto out;
    }
    *f_pos += count;
    ret = count;
    /* update the size */
    if (dev->size < *f_pos)
        dev-> size = *f_pos;
  out:
    up(&dev->sem);
    return ret;
}
/*
 * The ioctl() implementation
 *
 * This is done twice, once the 2.2 way, followed by the 2.0 way.  One
 * would not normally do things in this manner, but we wanted to illustrate
 * both ways...
 */
#ifndef LINUX_20
int scull_ioctl(struct inode *inode, struct file *filp,
                 unsigned int cmd, unsigned long arg)
{
struct Scull_Dev *dev=filp->private_data;
    int err = 0, tmp;
 char temp;
 int dev_size=cmd,new_size,i,j;
    int ret = 0;
  
    /*
     * extract the type and number bitfields, and don't decode
     * wrong cmds: return ENOTTY (inappropriate ioctl) before access_ok()
     */
    if (_IOC_TYPE(cmd) != SCULL_IOC_MAGIC) return -ENOTTY;
    if (_IOC_NR(cmd) > SCULL_IOC_MAXNR) return -ENOTTY;
    /*
     * the direction is a bitmask, and VERIFY_WRITE catches R/W
     * transfers. `Type' is user-oriented, while
     * access_ok is kernel-oriented, so the concept of "read" and
     * "write" is reversed
     */
    if (_IOC_DIR(cmd) & _IOC_READ)
        err = !access_ok(VERIFY_WRITE, (void *)arg, _IOC_SIZE(cmd));
    else if (_IOC_DIR(cmd) & _IOC_WRITE)
        err =  !access_ok(VERIFY_READ, (void *)arg, _IOC_SIZE(cmd));
    if (err) return -EFAULT;
    switch(cmd) {
#ifdef SCULL_DEBUG
      case SCULL_IOCHARDRESET:
         /*
          * reset the counter to 1, to allow unloading in case
          * of problems. Use 1, not 0, because the invoking
          * process has the device open.
          */
         while (MOD_IN_USE)
             MOD_DEC_USE_COUNT;
         MOD_INC_USE_COUNT;
         /* don't break: fall through and reset things */
#endif /* SCULL_DEBUG */
      case SCULL_IOCRESET:
        scull_quantum = SCULL_QUANTUM;
        scull_qset = SCULL_QSET;
        break;
      
      case SCULL_IOCSQUANTUM: /* Set: arg points to the value */
        if (! capable (CAP_SYS_ADMIN))
            return -EPERM;
        ret = __get_user(scull_quantum, (int *)arg);
        break;
      case SCULL_IOCTQUANTUM: /* Tell: arg is the value */
        if (! capable (CAP_SYS_ADMIN))
            return -EPERM;
        scull_quantum = arg;
        break;
      case SCULL_IOCGQUANTUM: /* Get: arg is pointer to result */
        ret = __put_user(scull_quantum, (int *)arg);
        break;
      case SCULL_IOCQQUANTUM: /* Query: return it (it's positive) */
        return scull_quantum;
      case SCULL_IOCXQUANTUM: /* eXchange: use arg as pointer */
        if (! capable (CAP_SYS_ADMIN))
            return -EPERM;
        tmp = scull_quantum;
        ret = __get_user(scull_quantum, (int *)arg);
        if (ret == 0)
            ret = __put_user(tmp, (int *)arg);
        break;
      case SCULL_IOCHQUANTUM: /* sHift: like Tell + Query */
        if (! capable (CAP_SYS_ADMIN))
            return -EPERM;
        tmp = scull_quantum;
        scull_quantum = arg;
        return tmp;
      
      case SCULL_IOCSQSET:
        if (! capable (CAP_SYS_ADMIN))
            return -EPERM;
        ret = __get_user(scull_qset, (int *)arg);
        break;
      case SCULL_IOCTQSET:
        if (! capable (CAP_SYS_ADMIN))
            return -EPERM;
        scull_qset = arg;
        break;
      case SCULL_IOCGQSET:
        ret = __put_user(scull_qset, (int *)arg);
        break;
      case SCULL_IOCQQSET:
        return scull_qset;
      case SCULL_IOCXQSET:
        if (! capable (CAP_SYS_ADMIN))
            return -EPERM;
        tmp = scull_qset;
        ret = __get_user(scull_qset, (int *)arg);
        if (ret == 0)
            ret = put_user(tmp, (int *)arg);
        break;
      case SCULL_IOCHQSET:
        if (! capable (CAP_SYS_ADMIN))
            return -EPERM;
        tmp = scull_qset;
        scull_qset = arg;
        return tmp;
        /*
         * The following two change the buffer size for scullpipe.
         * The scullpipe device uses this same ioctl method, just to
         * write less code. Actually, it's the same driver, isn't it?
         */
      case SCULL_P_IOCTSIZE:
        scull_p_buffer = arg;
        break;
      case SCULL_P_IOCQSIZE:
        return scull_p_buffer;
 case SCULL_SORTFIRSTQUANT:
 if(!dev->data)
  return -EAGAIN;
 if(!dev->data[0])
  return -EAGAIN;
 if(dev_size < scull_quantum)
  new_size = dev_size;
 else
  new_size = scull_quantum;
printk("device size %d",dev_size);
 for(i=0;i<new_size;i++)
 {
  for(j=0;j<new_size;j++)
  {    if( (*((char*)dev->data[0]+j)) > (*((char*)dev->data[0]+j+1)))
   {
    temp = (*((char*)dev->data[0]+j));
    (*((char*)dev->data[0]+j))= (*((char*)dev->data[0]+j+1));
    (*((char*)dev->data[0]+j+1))=temp;
   }
  }
 }  break;
       default:  /* redundant, as cmd was checked against MAXNR */
        return -ENOTTY;
    }
    return ret;
}
#else  /* LINUX_20 */
int scull_ioctl(struct inode *inode, struct file *filp,
                 unsigned int cmd, unsigned long arg)
{
    int err = 0, tmp;
  
    /*
     * extract the type and number bitfields, and don't decode
     * wrong cmds: return ENOTTY before verify_area()
     */
    if (_IOC_TYPE(cmd) != SCULL_IOC_MAGIC) return -ENOTTY;
    if (_IOC_NR(cmd) > SCULL_IOC_MAXNR) return -ENOTTY;
    /*
     * the direction is a bitmask, and VERIFY_WRITE catches R/W
     * transfers. `Type' is user-oriented, while
     * verify_area is kernel-oriented, so the concept of "read" and
     * "write" is reversed
     */
    if (_IOC_DIR(cmd) & _IOC_READ)
        err = verify_area(VERIFY_WRITE, (void *)arg, _IOC_SIZE(cmd));
    else if (_IOC_DIR(cmd) & _IOC_WRITE)
        err =  verify_area(VERIFY_READ, (void *)arg, _IOC_SIZE(cmd));
    if (err) return err;
    switch(cmd) {
      case SCULL_IOCRESET:
        scull_quantum = SCULL_QUANTUM;
        scull_qset = SCULL_QSET;
        break;
      
      case SCULL_IOCSQUANTUM: /* Set: arg points to the value */
        scull_quantum = get_user((int *)arg);
        break;
      case SCULL_IOCTQUANTUM: /* Tell: arg is the value */
        scull_quantum = arg;
        break;
      case SCULL_IOCGQUANTUM: /* Get: arg is pointer to result */
        put_user(scull_quantum, (int *)arg);
        break;
      case SCULL_IOCQQUANTUM: /* Query: return it (it's positive) */
        return scull_quantum;
      case SCULL_IOCXQUANTUM: /* eXchange: use arg as pointer */
        tmp = scull_quantum;
        scull_quantum = get_user((int *)arg);
        put_user(tmp, (int *)arg);
        break;
      case SCULL_IOCHQUANTUM: /* sHift: like Tell + Query */
        tmp = scull_quantum;
        scull_quantum = arg;
        return tmp;
      
      case SCULL_IOCSQSET:
        scull_qset = get_user((int *)arg);
        break;
      case SCULL_IOCTQSET:
        scull_qset = arg;
        break;
      case SCULL_IOCGQSET:
        put_user(scull_qset, (int *)arg);
        break;
      case SCULL_IOCQQSET:
        return scull_qset;
      case SCULL_IOCXQSET:
        tmp = scull_qset;
        scull_qset = get_user((int *)arg);
        put_user(tmp, (int *)arg);
        break;
      case SCULL_IOCHQSET:
        tmp = scull_qset;
        scull_quantum = arg;
        return tmp;
        /*
         * The following two change the buffer size for scullpipe.
         * The scullpipe device uses this same ioctl method, just to
         * write less code. Actually, it's the same driver, isn't it?
         */
      case SCULL_P_IOCTSIZE:
        scull_p_buffer = arg;
        break;
      case SCULL_P_IOCQSIZE:
        return scull_p_buffer;

      default:  /* redundant, as cmd was checked against MAXNR */
        return -ENOTTY;
    }
    return 0;
}

#endif /* LINUX_20 */

/*
 * The "extended" operations -- only seek
 */
loff_t scull_llseek(struct file *filp, loff_t off, int whence)
{
    Scull_Dev *dev = filp->private_data;
    loff_t newpos;
    switch(whence) {
      case 0: /* SEEK_SET */
        newpos = off;
        break;
      case 1: /* SEEK_CUR */
        newpos = filp->f_pos + off;
        break;
      case 2: /* SEEK_END */
        newpos = dev->size + off;
        break;
      default: /* can't happen */
        return -EINVAL;
    }
    if (newpos<0) return -EINVAL;
    filp->f_pos = newpos;
    return newpos;
}

/*
 * The following wrappers are meant to make things work with 2.0 kernels
 */
#ifdef LINUX_20
int scull_lseek_20(struct inode *ino, struct file *f,
                off_t offset, int whence)
{
    return (int)scull_llseek(f, offset, whence);
}
int scull_read_20(struct inode *ino, struct file *f, char *buf, int count)
{
    return (int)scull_read(f, buf, count, &f->f_pos);
}
int scull_write_20(struct inode *ino, struct file *f, const char *b, int c)
{
    return (int)scull_write(f, b, c, &f->f_pos);
}
void scull_release_20(struct inode *ino, struct file *f)
{
    scull_release(ino, f);
}
/* Redefine "real" names to the 2.0 ones */
#define scull_llseek scull_lseek_20
#define scull_read scull_read_20
#define scull_write scull_write_20
#define scull_release scull_release_20
#define llseek lseek
#endif  /* LINUX_20 */
struct file_operations scull_fops = {
    llseek:     scull_llseek,
    read:       scull_read,
    write:      scull_write,
    ioctl:      scull_ioctl,
    open:       scull_open,
    release:    scull_release,
};
/*
 * Finally, the module stuff
 */
#ifdef CONFIG_DEVFS_FS
devfs_handle_t scull_devfs_dir;
static char devname[4];
#endif
/*
 * The cleanup function is used to handle initialization failures as well.
 * Thefore, it must be careful to work correctly even if some of the items
 * have not been initialized
 */
void scull_cleanup_module(void)
{
    int i;
#ifndef CONFIG_DEVFS_FS
    /* cleanup_module is never called if registering failed */
    unregister_chrdev(scull_major, "scull");
#endif
#ifdef SCULL_DEBUG /* use proc only if debugging */
    scull_remove_proc();
#endif
    if (scull_devices) {
        for (i=0; i<scull_nr_devs; i++) {
            scull_trim(scull_devices+i);
            /* the following line is only used for devfs */
            devfs_unregister(scull_devices[i].handle);
        }
        kfree(scull_devices);
    }
    /* and call the cleanup functions for friend devices */
    scull_p_cleanup();
    scull_access_cleanup();
    /* once again, only for devfs */
    devfs_unregister(scull_devfs_dir);
}

int scull_init_module(void)
{
    int result, i;
    SET_MODULE_OWNER(&scull_fops);
#ifdef CONFIG_DEVFS_FS
    /* If we have devfs, create /dev/scull to put files in there */
    scull_devfs_dir = devfs_mk_dir(NULL, "scull", NULL);
    if (!scull_devfs_dir) return -EBUSY; /* problem */
#else /* no devfs, do it the "classic" way  */ 

    /*
     * Register your major, and accept a dynamic number. This is the
     * first thing to do, in order to avoid releasing other module's
     * fops in scull_cleanup_module()
     */
    result = register_chrdev(scull_major, "scull", &scull_fops);
    if (result < 0) {
        printk(KERN_WARNING "scull: can't get major %d\n",scull_major);
        return result;
    }
    if (scull_major == 0) scull_major = result; /* dynamic */
#endif /* CONFIG_DEVFS_FS */
    /*
     * allocate the devices -- we can't have them static, as the number
     * can be specified at load time
     */
    scull_devices = kmalloc(scull_nr_devs * sizeof(Scull_Dev), GFP_KERNEL);
    if (!scull_devices) {
        result = -ENOMEM;
        goto fail;
    }
    memset(scull_devices, 0, scull_nr_devs * sizeof(Scull_Dev));
    for (i=0; i < scull_nr_devs; i++) {
        scull_devices[i].quantum = scull_quantum;
        scull_devices[i].qset = scull_qset;
        sema_init(&scull_devices[i].sem, 1);
#ifdef CONFIG_DEVFS_FS
        sprintf(devname, "%i", i);
        devfs_register(scull_devfs_dir, devname,
                       DEVFS_FL_AUTO_DEVNUM,
                       0, 0, S_IFCHR | S_IRUGO | S_IWUGO,
                       &scull_fops,
                       scull_devices+i);
#endif
    }
    /* At this point call the init function for any friend device */
    if ( (result = scull_p_init()) )
        goto fail;
    if ( (result = scull_access_init()) )
        goto fail;
    /* ... */
#ifndef SCULL_DEBUG
    EXPORT_NO_SYMBOLS; /* otherwise, leave global symbols visible */
#endif
#ifdef SCULL_DEBUG /* only when debugging */
    scull_create_proc();
#endif
    return 0; /* succeed */
  fail:
    scull_cleanup_module();
    return result;
}


module_init(scull_init_module);
module_exit(scull_cleanup_module);

//Be into the folder scull and copy this main.c into that ... and perform this commands
//make clean
//make
//sh scull_unload
//sh scull_load
//cat main.c>/dev/scull0
//cat main.c>/dev/scull1
//cat main.c>/dev/scull2
//cat main.c>/dev/scull3
//cat /proc/scull50