Showing posts with label Programming. Show all posts
Showing posts with label Programming. Show all posts

Sunday, 13 April 2014

Programming - File I/O

Though it's simple to handle file I/O in computer programming, it's really difficult to teach what are the files and how we perform input and output into those files, especially when I promised in pre-requisite of the tutorial that you do not need to know anything about computer.
OK, let's start with learning what are files in computer terminology?

Computer Files

A computer file is used to store data in digital format like plain text, image data or any other content. If you will have a look at this HTML file, name is computer_programming_file_io.htm and it's keeping HTML text, which you are reading. Similar way, we use digital image data in the form of files. This tutorial is using minilogo image with a file name cp-mini-logo.png. Computer files can be organized inside different directories. So, files are used to keep digital data where as directories are used to keep files.
Computer files can be considered as the digital counterpart of paper documents, which traditionally are kept in office. While doing programming, you keep your source code in text files with different extensions, for example, C programming files have .c extension, Java programming files have .java extension and Python programming file have extension as .py.

File Input/Output

Usually, you create files using text editors like notepad, MS Word, MS Excel or MS Powerpoint, etc., but many times, we need to create files using computer program as well. We can modify existing file using a computer program.
File input means data, which we write into a file and file output means data, which we read from a file. Actually, input and output terms are more related to screen input and output where we display our result on the screen which is called output and if we provide some input to our program from command prompt, then it's called input.
For now, it's enough to remember that writing into a file is file input and reading something from the file is file output.

File Operation Modes

Before we start playing with any file using our program, either we need to create a new file if it does not exist or open an already existing file. In either case, we can open a file in the following modes:
  • Read Only Mode: If you are going just to read an existing file and you do not want to write any further content in the file, then you will open file in read only mode. Almost, all the programming languages provide syntax to open file in read only mode.
  • Write Only Mode: If you are going to write into either an existing file or newly created file but you do not want to read any written content in the file, then you will open file in write only mode. All the programming languages provide syntax to open file in write only mode.
  • Read & Write Mode: If you are going to read as well as write into the same file, then you will open file in read & write mode. Almost, all the programming languages provide syntax to open file in read & write mode.
  • Append Mode: When you open a file for writing, it allows you to start writing your content from the beginning of the file but writing content from the beginning in a file, which already has some content, will overwrite already existing content. We prefer to open a file in such a way that we should start appending content in already existing content of the file. So in such situation, we open file in append mode. Append mode is ultimately a write mode, which allows content to be appended in the last of the file. Almost, all the programming languages provide syntax to open file in append mode.
Now, following section will teach you how to open a fresh new file, how to write content in that file and later how to read and append more content into the same file.

Opening Files

You can use the fopen( ) function to create a new file or to open an existing file, this call will initialize an object of the type FILE, which contains all the information necessary to control the stream. Following is the prototype, i.e., signature of this function call:
FILE *fopen( const char * filename, const char * mode );
Here, filename is string literal, which you will use to name your file and access mode can have one of the following values:


Mode
Description
r
Opens an existing text file for reading purpose.
w
Opens a text file for writing, if it does not exist then a new file is created. Here, your program will start writing content from the beginning of the file.
a
Opens a text file for writing in appending mode, if it does not exist then a new file is created. Here, your program will start appending content in the existing file content.
r+
Opens a text file for reading and writing both.
w+
Opens a text file for reading and writing both. It first truncate the file to zero length if it exists otherwise create the file if it does not exist.
a+
Opens a text file for reading and writing both. It creates the file if it does not exist. The reading will start from the beginning but writing can only be appended.









Closing a File

To close a file, use the fclose( ) function. The prototype i.e. signature of this function is:
 int fclose( FILE *fp );
The fclose( ) function returns zero on success, or EOF, special character, if there is an error in closing the file. This function actually flushes any data still pending in the buffer to the file, closes the file, and releases any memory used for the file. The EOF is a constant defined in the header file stdio.h.
There are various functions provided by C standard library to read and write a file character by character or in the form of a fixed length string. Let us see few of them in the next section.

Writing a File

Following is the simplest function to write individual characters to a stream:
int fputc( int c, FILE *fp );
The function fputc() writes the character value of the argument c to the output stream referenced by fp. It returns the written character written on success, otherwise EOF if there is an error. You can use the following functions to write a null-terminated string to a stream:
int fputs( const char *s, FILE *fp );
The function fputs() writes the string s into the file referenced by fp. It returns a non-negative value on success, otherwise EOF is returned in case of any error. You can use int fprintf(FILE *fp,const char *format, ...) function as well to write a string into a file. Try the following example:
#include <stdio.h>

main()
{
   FILE *fp;

   fp = fopen("/tmp/test.txt", "w+");
   fprintf(fp, "This is testing for fprintf...\n");
   fputs("This is testing for fputs...\n", fp);
   fclose(fp);
}
When the above code is compiled and executed, it creates a new file test.txt in /tmp directory and writes two lines using two different functions. Let us read this file in next section.

Reading a File

Following is the simplest function to read a text file character by character:
int fgetc( FILE * fp );
The fgetc() function reads a character from the input file referenced by fp. The return value is the character read, or in case of any error it returns EOF. The following functions allow you to read a string from a stream:
char *fgets( char *buf, int n, FILE *fp );
The functions fgets() reads up to n - 1 characters from the input stream referenced by fp. It copies the read string into the buffer buf, appending a null character to terminate the string.
If this function encounters a newline character '\n' or the end of the file EOF before they have read the maximum number of characters, then it returns only the characters read up to that point including new line character. You can also use int fscanf(FILE *fp, const char *format, ...) function to read strings from a file but it stops reading after the first space character encounters.
#include <stdio.h>

main()
{
   FILE *fp;
   char buff[255];

   fp = fopen("/tmp/test.txt", "r");
   fscanf(fp, "%s", buff);
   printf("1 : %s\n", buff );

   fgets(buff, 255, (FILE*)fp);
   printf("2: %s\n", buff );
   
   fgets(buff, 255, (FILE*)fp);
   printf("3: %s\n", buff );
   fclose(fp);

}
When the above code is compiled and executed, it reads the file created in previous section and produces the following result:
1 : This
2: is testing for fprintf...

3: This is testing for fputs...
Let's see a little more detail about what happened here. First fscanf() method read just This because after that it encountered a space, second call is for fgets(), which reads the remaining line till it encountered end of line. Finally, last call fgets() reads second line completely.

File I/O in Java

Java programming language provides even richer set of functions to handle File I/O. For a complete detail, I will suggest you to check Java Tutorial.
Here, we will see a simple Java program, which is equal to C program explained above. This program will open a text file and will write few text lines into that file and close the file. Finally, same file is opened and then read that text from already created file. You can try to execute following program to see the output:
import java.io.*;

public class DemoJava
{    
   public static void main(String []args) throws IOException
   {
   
      File file = new File("/tmp/java.txt");
      
      // Create a File
      file.createNewFile();
      
      //  Creates a FileWriter Object using file object
      FileWriter writer = new FileWriter(file); 
      
      // Writes the content to the file
      writer.write("This is testing for Java write...\n");
      writer.write("This is second line...\n");
      
      // Flush the memory and close the file
      writer.flush();
      writer.close();
      
      // Creates a FileReader Object
      FileReader reader = new FileReader(file); 
      char [] a = new char[100];
      
      // Read file content in the array
      reader.read(a);
      System.out.println( a );
      
      // Close the file
      reader.close();
   }
}
When above program is executed, it produces the following result:
This is testing for Java write...
This is second line...

File I/O in Python

Following program shows the same functionality to open new file, write some content into the file and finally read the same file:
# Create a new file
fo = open("/tmp/python.txt", "w")

# Writes the content to the file
fo.write( "This is testing for Python write...\n");
fo.write( "This is second line...\n");

# Close the file
fo.close()

# Open existing file
fo = open("/tmp/python.txt", "r")

# Read file content in a variable
str = fo.read(100);
print str

# Close opened file
fo.close()
When the above code is executed, it produces the following result:
This is testing for Python write...
This is second line...

Programming - Functions

A function is a block of organized, reusable code that is used to perform a single, related action. Functions provide better modularity for your application and a high degree of code reusing. You already have seen various functions like printf() and main(). These are called built-in functions provided by the language itself, but we can write our own functions as well and this tutorial will teach you how to write and use those functions in C programming language.
Good thing about functions is that they are famous with several names. Different programming languages name them differently like functions, methods, sub-routines, procedures, etc. So when you come across any such terminology, then just imagine about the same concept, which we are going to discuss in this tutorial.
Let's start with a program where we will define two arrays of numbers and then from each array, we will find the biggest number. As we already have seen following are the steps to find out maximum number from a given set of numbers:
1.      Get a list of numbers L1, L2, L3....LN
2.      Assume L1 is the largest,  Set max = L1
3.	Take next number Li from the list and do the following
4.      If max is less than Li
5.         Set max = Li
6.      If Li is last number from  the list then
7.         Print value stored in max and come out
8.      Else prepeat same process starting from step 3
Let's translate above program in C programming language:
#include <stdio.h>

main()
{
    int set1[5] = {10, 20, 30, 40, 50};
    int set2[5] = {101, 201, 301, 401, 501};
    int i, max;
   
    /* Process first set of numbers available in set1[] */
    max = set1[0];
    i = 1;    
    while( i < 5 )
    {
        if( max <  set1[i] )
        {
            max = set1[i];
        }
        i = i + 1;
    }
    printf("Max in first set = %d\n", max );
    
    /* Now process second set of numbers available in set2[] */
    max = set2[0];
    i = 1;    
    while( i < 5 )
    {
        if( max <  set2[i] )
        {
            max = set2[i];
        }
        i = i + 1;
    }
    printf("Max in second set = %d\n", max );
}
When the above code is compiled and executed, it produces the following result:
Max in first set = 50
Max in second set = 501
If you are clear about the above example, then it will become easy to understand why do we need a function. Here in above example, I took only two sets of numbers set1, and set2 but consider a situation we have 10 or more similar sets of numbers to find out maximum numbers from each set. In such situation, we will have to repeat same processing 10 or more times and ultimately program will become too large with repeated code. To handle such situation, we write our functions where we try to keep source code which will be used again and again in our programming.
Now, let's see how to define a function in C programming language and then subsequent section will explain how to use that function:

Defining a Function:

The general form of a function definition in C programming language is as follows:
return_type function_name( parameter list )
{
   body of the function
   
   return [expression];
}
A function definition in C programming language consists of a function header and a function body. Here are all the parts of a function:
  • Return Type: A function may return a value. The return_type is the data type of the value the function returns. Some functions perform the desired operations without returning a value. In this case, the return_type is the keyword void.
  • Function Name: This is the actual name of the function. The function name and the parameter list together constitute the function signature.
  • Parameter List: A parameter is like a placeholder. When a function is invoked, you pass a value as a parameter. This value is referred to as actual parameter or argument. The parameter list refers to the type, order, and number of the parameters of a function. Parameters are optional; that is, a function may contain no parameters.
  • Function Body: The function body contains a collection of statements that define what the function does.

Calling a Function:

While creating a C function, you give a definition of what the function has to do. To use a function, you will have to call that function to perform the defined task.
Now, let's write above example with the help of a function:
#include <stdio.h>

int getMax( int set[] )
{
   int i, max;
   
    max = set[0];
    i = 1;    
    while( i < 5 )
    {
        if( max <  set[i] )
        {
            max = set[i];
        }
        i = i + 1;
    }
    
    return max;
}

main()
{
    int set1[5] = {10, 20, 30, 40, 50};
    int set2[5] = {101, 201, 301, 401, 501};
    int max;

    /* Process first set of numbers available in set1[] */
    max = getMax(set1);
    printf("Max in first set = %d\n", max );
    
    /* Now process second set of numbers available in set2[] */
    max = getMax(set2);
    printf("Max in second set = %d\n", max );
}
When the above code is compiled and executed, it produces the following result:
Max in first set = 50
Max in second set = 501
For now, its enough for you to know about what are functions and how do they work. If you understood this concept then you can proceed for a detailed tutorial to drill it down further.

Functions in Java

If you are clear about functions in C programming, then its easy to understand them in Java as well. Java programming names them as methods , but rest of the concepts remain more or less same as we discussed in C programming.
Following is the equivalent program written in Java programming language. You can try to execute the following program to see the output:
public class DemoJava
{    
   public static void main(String []args) 
   {
      int[] set1 = {10, 20, 30, 40, 50};
      int[] set2 = {101, 201, 301, 401, 501};
      int max;

      /* Process first set of numbers available in set1[] */
      max = getMax(set1);
      System.out.format("Max in first set = %d\n", max );

      /* Now process second set of numbers available in set2[] */
      max = getMax(set2);
      System.out.format("Max in second set = %d\n", max );
   }
   
   public static int getMax( int set[] )
   {
       int i, max;
   
       max = set[0];
       i = 1;    
       while( i < 5 )
       {
           if( max <  set[i] )
           {
               max = set[i];
           }
           i = i + 1;
       }
    
       return max;
   }
}
When above program is executed, it produces the following result:
Max in first set = 50
Max in second set = 501

Functions in Python

Once again, if you already understood the concept of functions in C and Java programming, then Python is not much different in defining and calling functions. Following is basic syntax of defining a function in Python:
def function_name( parameter list ):
   body of the function
   
   return [expression]
So using this syntax of function in Python, above example can be written as follows:
def getMax( set ):
    max = set[0]
    i = 1   
    while( i < 5 ):
        if( max <  set[i] ):
            max = set[i]
        i = i + 1
    return max


set1 = [10, 20, 30, 40, 50]
set2 = [101, 201, 301, 401, 501]

# Process first set of numbers available in set1[]
max = getMax(set1)
print "Max in first set = ", max
    
# Now process second set of numbers available in set2[]
max = getMax(set2)
print "Max in second set = ", max
When the above code is executed, it produces the following result:
Max in first set =  50
Max in second set =  501

Saturday, 12 April 2014

Programming - Strings

During our discussion about characters in computer programming, we learnt that character data type deals with a single character and you can assign any character from your keyboard to a character type variable.
Now, let's move a little bit ahead and consider a situation where we need to store more than one character in a variable. We have seen that C programming does not allow to store more than one character in a character type variable. So following statements are invalid in C programming and produce syntax error:
char ch1 = 'ab';
char ch2 = '10';
We also have seen how we can store more than one value of similar data type in a variable using array concept. If recap then, here is the syntax to store and print 5 numbers in an array of int type:
#include <stdio.h>

main()
{
    int number[5] = {10, 20, 30, 40, 50};
    int i = 0;
        
    while( i < 5 )
    {
        printf("number[%d] = %d\n", i, number[i] );
        i = i + 1;
   }
}
When the above code is compiled and executed, it produces the following result:
number[0] = 10
number[1] = 20
number[2] = 30
number[3] = 40
number[4] = 50
Now, let's define an array of 5 characters in the similar way as we did for numbers and try to print them:
#include <stdio.h>

main()
{
    char ch[5] = {'H', 'e', 'l', 'l', 'o'};
    int i = 0;
        
    while( i < 5 )
    {
        printf("ch[%d] = %c\n", i, ch[i] );
        i = i + 1;
   }
}
Here, we used %c to print character value. When the above code is compiled and executed, it produces the following result:
ch[0] = H
ch[1] = e
ch[2] = l
ch[3] = l
ch[4] = o
If you are done with the above example, then I think you understood about strings in C programming, because strings in C are represented as arrays of characters. C programming simplified the assignment and printing of strings. Let's check same example once again with simplified syntax:
#include <stdio.h>

main()
{
    char ch[5] = "Hello";
    int i = 0;
    
    /* Print as a complete string */
    printf("String = %s\n", ch);  
    
    /* Print character by character */
    while( i < 5 )
    {
        printf("ch[%d] = %c\n", i, ch[i] );
        i = i + 1;
   }
}
Here, we used %s to print full string value using array name ch, which is actually beginning of the memory address holding ch variable as shown below:
String Presentation in C/C++ Though it's not visible from the above examples, but internally C program assigns null character '\0' as the last character of every string. This indicates the end of the string and it means if you want to store a 5 character string in an array then you must define array size of 6 as a good practice, though C does not complain about it.
Now if the above code is compiled and executed, it produces the following result:
String = Hell
ch[0] = H
ch[1] = e
ch[2] = l
ch[3] = l
ch[4] = o

Basic String Concepts

Based on the above discussion we can conclude the following important points to remember about strings in C programming language:
  • Strings in C are represented as arrays of characters.
  • We can constitute a string in C programming by assigning character by character into an array of characters.
  • We can constitute a string in C programming by assigning a complete string enclosed in double quote.
  • We can print a string character by character using array subscript or a complete string by using array name without subscript.
  • Though it's not visible from the above examples, but internally C program assigns null character '\0' as the last character of every string. This indicates the end of the string and it means if you want to store a 5-character string in an array then you must define array size of 6 as a good practice, though C does not complain about it.
  • Most of the programming languages provide built-in functions to manipulate strings, i.e., you can concatenate strings, you can search from a string, you can take sub string from the string. For a detail you can check detailed tutorial for C or other programming languages.

Strings in Java

Though you can use character array to store strings but Java is an advanced programming language and its designers tried to provide additional functionality like Java provides string as a built-in data type like any other data type. So it means you can define strings directly instead of defining them array of characters.
Following is the equivalent program written in Java programming language. Java programming makes use of new operator to create string variable as shown below in the program:
You can try to execute the following program to see the output:
public class DemoJava
{    
   public static void main(String []args) 
   {
       String str = new String("Hello");  
       
       System.out.println( "String = " + str );
   }
}
When above program is executed, it produces the following result:
String = Hello

Strings in Python

Creating strings in Python is as simple as simply assigning a string into a Python variable using single or double quote as shown below:
Following is a simple program, which creates two strings and print them using print() function:
var1 = 'Hello World!'
var2 = "Python Programming"

print "var1 = ", var1
print "var2 = ", var2
When above program is executed, it produces the following result:
var1 =  Hello World!
var2 =  Python Programming
Python does not support a character type; these are treated as strings of length one, thus also considered a substring.
To access substrings, use the square brackets for slicing along with the index or indices to obtain your substring. Following is a simple example:
var1 = 'Hello World!'
var2 = "Python Programming"

print "var1[0]: ", var1[0]
print "var2[1:5]: ", var2[1:5]
When the above code is executed, it produces the following result:
var1[0]:  H
var2[1:5]:  ytho

Programming - Arrays

Consider a situation, where we need to store 5 integer numbers. If we use programming's simple variable and data type concepts, then we need 5 variables of int data type and program will be something as follows:
#include <stdio.h>

main()
{
   int  number1;
   int  number2;
   int  number3;
   int  number4;
   int  number5;
   
   number1 = 10;      
   number2 = 20;   
   number3 = 30;   
   number4 = 40; 
   number5 = 50;     

   printf( "number1: %d\n", number1);
   printf( "number2: %d\n", number2);
   printf( "number3: %d\n", number3);
   printf( "number4: %d\n", number4);
   printf( "number5: %d\n", number5);
}
It was simple, because we had to store just 5 integer numbers. Now let's assume we have to store 5000 integer numbers, so what is next? Are we going to use 5000 variables?
To handle such situation, almost all the programming languages provide a concept called the array. An array is a data structure, which can store a fixed-size collection of elements of the same data type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type.
So instead of declaring individual variables, such as number1, number2, ..., and number99, you just declare one array variable number of integer type and use number1[0], number1[1], and ..., number1[99] to represent individual variables. Here, 0, 1, 2, .....99 are index associated with var variable and they are being used to represent individual elements available in the array.
All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element.
Arrays in C

Create Arrays

To create an array variable in C, a programmer specifies the type of the elements and the number of elements to be stored in that array. Following is a simple syntax to create an array in C programming:
type arrayName [ arraySize ];
This is called a single-dimensional array. The arraySize must be an integer constant greater than zero and type can be any valid C data type. For example, now to declare a 10-element array called number of type int , use this statement:
int number[10];
Now, number is a variable array, which is sufficient to hold up to 10 integer numbers.

Initializing Arrays

You can initialize array in C either one by one or using a single statement as follows:
int number[5] = {10, 20, 30, 40, 50};
The number of values between braces { } cannot be larger than the number of elements that we declare for the array between square brackets [ ].
If you omit the size of the array, an array just big enough to hold the initialization is created. Therefore, if you write:
int number[] = {10, 20, 30, 40, 50};
You will create exactly the same array as you did in the previous example. Following is an example to assign a single element of the array:
number[4] = 50;
The above statement assigns element number 5th in the array with a value of 50. All arrays have 0 as the index of their first element which is also called base index and last index of an array will be total size of the array minus 1. Following is the pictorial representation of the same array we discussed above:
Array Presentation

Accessing Array Elements

An element is accessed by indexing the array name. This is done by placing the index of the element within square brackets after the name of the array. For example:
int var = number[9];
The above statement will take 10th element from the array and assign the value to var variable. Following is an example, which will use all the above-mentioned three concepts viz. creation, assignment and accessing arrays:
#include <stdio.h>
 
int main ()
{
   int number[10]; /* number is an array of 10 integers */
   int i = 0;
 
   /* Initialize elements of array n to 0 */         
   while( i < 10 )
   {
      /* Set element at location i to i + 100 */
      number[ i ] = i + 100;
      i = i + 1;
   }
   
   /* Output each array element's value */
   i = 0;
   while( i < 10 )
   {
      printf("number[%d] = %d\n", i, number[i] );
      i = i + 1;
   }
 
   return 0;
}
When the above code is compiled and executed, it produces the following result:
number[0] = 100
number[1] = 101
number[2] = 102
number[3] = 103
number[4] = 104
number[5] = 105
number[6] = 106
number[7] = 107
number[8] = 108
number[9] = 109

Arrays in Java

Following is the equivalent program written in Java programming language. Java programming language also supports array, but there is a little difference to create them in different ways using new operator available in Java programming language.
You can try to execute the following program to see the output, which must be identical to the result generated by the above C example.
public class DemoJava
{    
   public static void main(String []args) 
   {
      int[] number = new int[10];
      int i = 0;
      
      while( i < 10 )
      {
         number[ i ] = i + 100;
         i = i + 1;
      }

      i = 0;
      while( i < 10 )
      {
         System.out.format( "number[%d] = %d\n", i, number[i] );
         i = i + 1;
      }
   }
}
When above program is executed, it produces the following result:
number[0] = 100
number[1] = 101
number[2] = 102
number[3] = 103
number[4] = 104
number[5] = 105
number[6] = 106
number[7] = 107
number[8] = 108
number[9] = 109

Arrays (Lists) in Python

Python does not have a concept of Array, instead Python provides another data structure called list, which provides similar functionality as arrays in any other language.
Following is the equivalent program written in Python:
# Following defines an empty list.
number = []
i = 0

while i < 10:
   # Appending elements in the list
   number.append(i + 100)
   i = i + 1

i = 0
while i < 10:
   # Accessing elements from the list
   print "number[", i,  "] = ", number[ i ]
   i = i + 1
When above program is executed, it produces the following result:
number[ 0 ] =  100
number[ 1 ] =  101
number[ 2 ] =  102
number[ 3 ] =  103
number[ 4 ] =  104
number[ 5 ] =  105
number[ 6 ] =  106
number[ 7 ] =  107
number[ 8 ] =  108
number[ 9 ] =  109