Posted in C++/Python

File handling

Python too supports file handling and allows users to handle files i.e., to read and write files, along with many other file handling options, to operate on files. The concept of file handling has stretched over various other languages, but the implementation is either complicated or lengthy, but alike other concepts of Python, this concept here is also easy and short. Python treats file differently as text or binary and this is important. Each line of code includes a sequence of characters and they form text file. Each line of a file is terminated with a special character, called the EOL or End of Line characters like comma {,} or newline character. It ends the current line and tells the interpreter a new one has begun. Let’s start with Reading and Writing files.

Working of open() function

We use open () function in Python to open a file in read or write mode. As explained above, open ( ) will return a file object. To return a file object we use open() function along with two arguments, that accepts file name and the mode, whether to read or write. So, the syntax being: open(filename, mode). There are three kinds of mode, that Python provides and how files can be opened:

  •  r “, for reading.
  •  w “, for writing.
  •  a “, for appending.
  •  r+ “, for both reading and writing

One must keep in mind that the mode argument is not mandatory. If not passed, then Python will assume it to be “ r ” by default. Let’s look at this program and try to analyze how the read mode works:

#a file named "thanh", will be opened with the reading mode.
 file = open('thanh.txt', 'r') 
 This will print every line one by one in the file
 for each in file: 
     print (each) 

Working of read() mode

There is more than one way to read a file in Python. If you need to extract a string that contains all characters in the file then we can use file.read(). The full code would work like this:

#Python code to illustrate read() mode
 file = open("file.text", "r") 
 print file.read() 

Creating a file using write() mode

Let’s see how to create a file and how write mode works:
To manipulate the file, write the following in your Python environment:

#Python code to create a file
 file = open('geek.txt','w') 
 file.write("This is the write command") 
 file.write("It allows us to write in a particular file") 
 file.close() 
Advertisement
Posted in C++/Python

Python Regex

Regular Expression in Python with Examples | Set 1

Last Updated: 19-10-2020

Module Regular Expressions(RE) specifies a set of strings(pattern) that matches it. 
To understand the RE analogy, MetaCharacters are useful, important and will be used in functions of module re. 
There are a total of 14 metacharacters and will be discussed as they follow into functions: 

\   Used to drop the special meaning of character
    following it (discussed below)
[]  Represent a character class
^   Matches the beginning
$   Matches the end
.   Matches any character except newline
?   Matches zero or one occurrence.
|   Means OR (Matches with any of the characters
    separated by it.
*   Any number of occurrences (including 0 occurrences)
+   One or more occurrences
{}  Indicate number of occurrences of a preceding RE 
    to match.
()  Enclose a group of REs



  • Function compile() 
    Regular expressions are compiled into pattern objects, which have methods for various operations such as searching for pattern matches or performing string substitutions. 
     
#Module Regular Expression is imported using <strong>import</strong>().
 import re 
# compile() creates regular expression character class [a-e],
# which is equivalent to [abcde].
# class [abcde] will match with string with 'a', 'b', 'c', 'd', 'e'.
 p = re.compile('[a-e]') 
# findall() searches for the Regular Expression and return a list upon finding
 print(p.findall("Aye, said Mr. Gibenson Stark")) 

Output: 

['e', 'a', 'd', 'b', 'e', 'a']




Understanding the Output: 
First occurrence is ‘e’ in “Aye” and not ‘A’, as it being Case Sensitive. 
Next Occurrence is ‘a’ in “said”, then ‘d’ in “said”, followed by ‘b’ and ‘e’ in “Gibenson”, the Last ‘a’ matches with “Stark”.
Metacharacter backslash ‘\’ has a very important role as it signals various sequences. If the backslash is to be used without its special meaning as metacharacter, use’\\’

\d   Matches any decimal digit, this is equivalent
     to the set class [0-9].
\D   Matches any non-digit character.
\s   Matches any whitespace character.
\S   Matches any non-whitespace character
\w   Matches any alphanumeric character, this is
     equivalent to the class [a-zA-Z0-9_].
\W   Matches any non-alphanumeric character. 
Posted in C++/Python

File Handling

In C++, files are mainly dealt by using three classes fstream, ifstream, ofstream available in fstream headerfile.
ofstream: Stream class to write on files
ifstream: Stream class to read from files
fstream: Stream class to both read and write from/to files.

Now the first step to open the particular file for read or write operation. We can open file by
1. passing file name in constructor at the time of object creation
2. using the open method
For e.g.

Open File by using constructor
ifstream (const char* filename, ios_base::openmode mode = ios_base::in);
ifstream fin(filename, openmode) by default openmode = ios::in
ifstream fin(“filename”);

Open File by using open method
Calling of default constructor
ifstream fin;

fin.open(filename, openmode)
fin.open(“filename”);

Modes :

MEMBER CONSTANTSTANDS FORACCESS
in *inputFile open for reading: the internal stream buffer supports input operations.
outoutputFile open for writing: the internal stream buffer supports output operations.
binarybinaryOperations are performed in binary mode rather than text.
ateat endThe output position starts at the end of the file.
appappendAll output operations happen at the end of the file, appending to its existing contents.
trunctruncateAny contents that existed in the file before it is open are discarded.

Default Open Modes :

ifstreamios::in
ofstreamios::out
fstreamios::in | ios::out

Below is the implementation by using fstream class.:

/* File Handling with C++ using ifstream & ofstream class object*/
/* To write the Content in File*/
/* Then to read the content of file*
#include <iostream>
/* fstream header file for ifstream, ofstream,  
fstream classes */
#include <fstream> 
using namespace std;

// Creation of ofstream class object
int main()
string line; 
ofstream fout;
// by default ios::out mode, automatically deletes 
// the content of file. To append the content, open in ios:app 
// fout.open("sample.txt", ios::app) 
fout.open("sample.txt"); 

// Execute a loop If file successfully opened 
while (fout) { 

    // Read a Line from standard input 
    getline(cin, line); 

    // Press -1 to exit 
    if (line == "-1") 
        break; 

    // Write line in file 
    fout << line << endl; 
} 

// Close the File 
fout.close(); 

// Creation of ifstream class object to read the file 
ifstream fin; 

// by default open mode = ios::in mode 
fin.open("sample.txt"); 

// Execute a loop until EOF (End of File) 
while (fin) { 

    // Read a Line from File 
    getline(fin, line); 

    // Print line in Console 
    cout << line << endl; 
} 

// Close the file 
fin.close(); 

return 0; 
Posted in C++/Python

Standard Template Library (STL)

The Standard Template Library (STL) is a set of C++ template classes to provide common programming data structures and functions such as lists, stacks, arrays, etc. It is a library of container classes, algorithms, and iterators. It is a generalized library and so, its components are parameterized. A working knowledge of template classes is a prerequisite for working with STL.

STL has four components

  • Algorithms
  • Containers
  • Functions
  • Iterators

Algorithms

The header algorithm defines a collection of functions especially designed to be used on ranges of elements.They act on containers and provide means for various operations for the contents of the containers.

Containers

Containers or container classes store objects and data. There are in total seven standard “first-class” container classes and three container adaptor classes and only seven header files that provide access to these containers or container adaptors.

Functions

The STL includes classes that overload the function call operator. Instances of such classes are called function objects or functors. Functors allow the working of the associated function to be customized with the help of parameters to be passed.

Iterators

As the name suggests, iterators are used for working upon a sequence of values. They are the major feature that allow generality in STL.

Posted in C++/Python

Constructors & Destructors

What is constructor? 
A constructor is a member function of a class which initializes objects of a class. In C++, Constructor is automatically called when object(instance of class) create. It is special member function of the class.
How constructors are different from a normal member function?

A constructor is different from normal functions in following ways: 

  • Constructor has same name as the class itself
  • Constructors don’t have return type
  • A constructor is automatically called when an object is created.
  • If we do not specify a constructor, C++ compiler generates a default constructor for us (expects no parameters and has an empty body).

Let us understand the types of constructors in C++ by taking a real-world example. Suppose you went to a shop to buy a marker. When you want to buy a marker, what are the options? The first one you go to a shop and say give me a marker. So just saying give me a marker mean that you did not set which brand name and which color, you didn’t mention anything just say you want a marker. So when we said just I want a marker so whatever the frequently sold marker is there in the market or in his shop he will simply hand over that. And this is what a default constructor is! The second method you go to a shop and say I want a marker a red in color and XYZ brand. So you are mentioning this and he will give you that marker. So in this case you have given the parameters. And this is what a parameterized constructor is! Then the third one you go to a shop and say I want a marker like this(a physical marker on your hand). So the shopkeeper will see that marker. Okay, and he will give a new marker for you. So copy of that marker. And that’s what copy constructor is!
Types of Constructors

  1. Default Constructors: Default constructor is the constructor which doesn’t take any argument. It has no parameters.

// Cpp program to illustrate the
// concept of Constructors

include using namespace std; class construct { public: int a, b; // Default Constructor construct() { a = 10; b = 20; } }; int main() { // Default constructor called automatically // when the object is created
Posted in C++/Python

Basic Input/Output

In C, we could use the function freopen() to redirect an existing FILE pointer to another stream. The prototype for freopen() is given as

FILE * freopen ( const char * filename, const char * mode, FILE * stream );

For Example to redirect the stdout to say a textfile, we could write

freopen ("text_file.txt", "w", stdout);

While this method is still supported in C++, this article discusses another way to redirect I/O streams.

C++ being an object-oriented programming language gives us the ability to not only define our own streams but also redirect standard streams. Thus in C++, a stream is an object whose behavior is defined by a class. Thus anything that behaves like a stream is also a stream.

Streams Objects in C++ are mainly of three types :

  • istream : Stream object of this type can only perform input operations from the stream
  • ostream : These objects can only be used for output operations.
  • iostream : Can be used for both input and output operations

All these classes, as well as file stream classes, derive from the classes: ios and streambuf. Thus filestream and IO stream objects behave similarly.

All stream objects also have an associated data member of class streambuf. Simply put streambuf object is the buffer for the stream. When we read data from a stream, we don’t read it directly from the source, but instead, we read it from the buffer which is linked to the source. Similarly, output operations are first performed on the buffer, and then the buffer is flushed (written to the physical device) when needed.

C++ allows us to set the stream buffer for any stream. So the task of redirecting the stream simply reduces to changing the stream buffer associated with the stream. Thus the to redirect a Stream A to Stream B we need to do

  1. Get the stream buffer of A and store it somewhere
  2. Set the stream buffer of A to the stream buffer of B
  3. If needed reset the stream buffer of A to its previous stream buffer

We can use the function ios::rdbuf() to perform two opeations.

1) stream_object.rdbuf(): Returns pointer to the stream buffer of stream_object
2) stream_object.rdbuf(streambuf * p): Sets the stream buffer to the object pointed by p

Posted in C++/Python

Operator

Operators are the foundation of any programming language. Thus the functionality of C/C++ programming language is incomplete without the use of operators. We can define operators as symbols that help us to perform specific mathematical and logical computations on operands. In other words, we can say that an operator operates the operands.
For example, consider the below statement:

c = a + b;

Here, ‘+’ is the operator known as addition operator and ‘a’ and ‘b’ are operands. The addition operator tells the compiler to add both of the operands ‘a’ and ‘b’.

C/C++ has many built-in operator types and they are classified as follows:

  1. Arithmetic Operators: These are the operators used to perform arithmetic/mathematical operations on operands. Examples: (+, -, *, /, %,++,–). Arithmetic operator are of two types:
    1. Unary Operators: Operators that operates or works with a single operand are unary operators. For example: (++ , –)
    2. Binary Operators: Operators that operates or works with two operands are binary operators. For example: (+ , – , * , /)
    To learn Arithmetic Operators in details visit this link.
  2. Relational Operators: These are used for comparison of the values of two operands. For example, checking if one operand is equal to the other operand or not, an operand is greater than the other operand or not etc. Some of the relational operators are (==, >= , <= ). To learn about each of these operators in details go to this link.
  3. Logical Operators:  Logical Operators are used to combine two or more conditions/constraints or to complement the evaluation of the original condition in consideration. The result of the operation of a logical operator is a boolean value either true or false. For example, the logical AND represented as ‘&&’ operator in C or C++ returns true when both the conditions under consideration are satisfied. Otherwise it returns false. Therfore, a && b returns true when both a and b are true (i.e. non-zero). To learn about different logical operators in details please visit this link.
  4. Bitwise Operators: The Bitwise operators is used to perform bit-level operations on the operands. The operators are first converted to bit-level and then the calculation is performed on the operands. The mathematical operations such as addition, subtraction, multiplication etc. can be performed at bit-level for faster processing. For example, the bitwise AND represented as & operator in C or C++ takes two numbers as operands and does AND on every bit of two numbers. The result of AND is 1 only if both bits are 1. To learn bitwise operators in details, visit this link.
  5. Assignment Operators: Assignment operators are used to assign value to a variable. The left side operand of the assignment operator is a variable and right side operand of the assignment operator is a value. The value on the right side must be of the same data-type of variable on the left side otherwise the compiler will raise an error.
    Different types of assignment operators are shown below:
    1. “=”: This is the simplest assignment operator. This operator is used to assign the value on the right to the variable on the left.
      For example:a = 10; b = 20; ch = ‘y’;
    2. “+=”: This operator is combination of ‘+’ and ‘=’ operators. This operator first adds the current value of the variable on left to the value on right and then assigns the result to the variable on the left.
      Example:(a += b) can be written as (a = a + b) If initially value stored in a is 5. Then (a += 6) = 11.
    3. “-=”: This operator is combination of ‘-‘ and ‘=’ operators. This operator first subtracts the value on right from the current value of the variable on left and then assigns the result to the variable on the left.
      Example:(a -= b) can be written as (a = a – b) If initially value stored in a is 8. Then (a -= 6) = 2.
    4. “*=”: This operator is combination of ‘*’ and ‘=’ operators. This operator first multiplies the current value of the variable on left to the value on right and then assigns the result to the variable on the left.
      Example:(a *= b) can be written as (a = a * b) If initially value stored in a is 5. Then (a *= 6) = 30.
    5. “/=”: This operator is combination of ‘/’ and ‘=’ operators. This operator first divides the current value of the variable on left by the value on right and then assigns the result to the variable on the left.
      Example:(a /= b) can be written as (a = a / b) If initially value stored in a is 6. Then (a /= 2) = 3.
  6. Other Operators: Apart from the above operators there are some other operators available in C or C++ used to perform some specific task. Some of them are discussed here:
    1. sizeof operator: sizeof is a much used in the C/C++ programming language. It is a compile time unary operator which can be used to compute the size of its operand. The result of sizeof is of unsigned integral type which is usually denoted by size_t. Basically, sizeof operator is used to compute the size of the variable. To learn about sizeof operator in details you may visit this link.
    2. Comma Operator: The comma operator (represented by the token ,) is a binary operator that evaluates its first operand and discards the result, it then evaluates the second operand and returns this value (and type). The comma operator has the lowest precedence of any C operator. Comma acts as both operator and separator. To learn about comma in details visit this link.
    3. Conditional Operator: Conditional operator is of the form Expression1 ? Expression2 : Expression3 . Here, Expression1 is the condition to be evaluated. If the condition(Expression1) is True then we will execute and return the result of Expression2 otherwise if the condition(Expression1) is false then we will execute and return the result of Expression3. We may replace the use of if..else statements by conditional operators. To learn about conditional operators in details, visit this link.

Operator precedence chart

The below table describes the precedence order and associativity of operators in C / C++ . Precedence of operator decreases from top to bottom.

OPERATORDESCRIPTIONASSOCIATIVITY
()Parentheses (function call)left-to-right
[]Brackets (array subscript)
.Member selection via object name
->Member selection via pointer
++/–Postfix increment/decrement
++/–Prefix increment/decrementright-to-left
+/-Unary plus/minus
!~Logical negation/bitwise complement
(type)Cast (convert value to temporary value of type)
*Dereference
&Address (of operand)
sizeofDetermine size in bytes on this implementation
*,/,%Multiplication/division/modulusleft-to-right
+/-Addition/subtractionleft-to-right
<< , >>Bitwise shift left, Bitwise shift rightleft-to-right
< , <=Relational less than/less than or equal toleft-to-right
> , >=Relational greater than/greater than or equal toleft-to-right
== , !=Relational is equal to/is not equal toleft-to-right
&Bitwise ANDleft-to-right
^Bitwise exclusive ORleft-to-right
|Bitwise inclusive ORleft-to-right
&&Logical ANDleft-to-right
||Logical ORleft-to-right
?:Ternary conditionalright-to-left
=Assignmentright-to-left
+= , -=Addition/subtraction assignment
*= , /=Multiplication/division assignment
%= , &=Modulus/bitwise AND assignment
^= , |=Bitwise exclusive/inclusive OR assignment
<>=Bitwise shift left/right assignment
,expression separatorleft-to-right
Posted in C++/Python

C++

C++ is a general-purpose programming language that was developed as an enhancement of the C language to include object-oriented paradigm. It is an imperative and a compiled language. 
 

C++ is a middle-level language rendering it the advantage of programming low-level (drivers, kernels) and even higher-level applications (games, GUI, desktop apps etc.). The basic syntax and code structure of both C and C++ are the same. 

Some of the features & key-points to note about the programming language are as follows:

  • Simple: It is a simple language in the sense that programs can be broken down into logical units and parts, has a rich libray support and a variety of data-types.
  • Machine Independent but Platform Dependent: A C++ executable is not platform-independent (compiled programs on Linux won’t run on Windows), however they are machine independent.
  • Mid-level language: It is a mid-level language as we can do both systems-programming (drivers, kernels, networking etc.) and build large-scale user applications (Media Players, Photoshop, Game Engines etc.)
  • Rich library support: Has a rich library support (Both standard ~ built-in data structures, algorithms etc.) as well 3rd party libraries (e.g. Boost libraries) for fast and rapid development.
  • Speed of execution: C++ programs excel in execution speed. Since, it is a compiled language, and also hugely procedural. Newer languages have extra in-built default features such as grabage-collection, dynamic typing etc. which slow the execution of the program overall. Since there is no additional processing overhead like this in C++, it is blazing fast.
  • Pointer and direct Memory-Access: C++ provides pointer support which aids users to directly manipulate storage address. This helps in doing low-level programming (where one might need to have explicit control on the storage of variables).
  • Object-Oriented: One of the strongest points of the language which sets it apart from C. Object-Oriented support helps C++ to make maintainable and extensible programs. i.e. Large-scale applications can be built. Procedural code becomes difficult to maintain as code-size grows.
  • Compiled Language: C++ is a compiled language, contributing to its speed.

Applications of C++: 
C++ finds varied usage in applications such as:

  • Operating Systems & Systems Programming. e.g. Linux-based OS (Ubuntu etc.)
  • Browsers (Chrome & Firefox)
  • Graphics & Game engines (Photoshop, Blender, Unreal-Engine)
  • Database Engines (MySQL, MongoDB, Redis etc.)
  • Cloud/Distributed Systems

Some interesting facts about C++: 
Here are some awesome facts about C++ that may interest you:

  1. The name of C++ signifies the evolutionary nature of the changes from C. “++” is the C increment operator.
  2. C++ is one of the predominant languages for the development of all kind of technical and commercial software.
  3. C++ introduces Object-Oriented Programming, not present in C. Like other things, C++ supports the four primary features of OOP: encapsulation, polymorphism, abstraction, and inheritance.
  4. C++ got the OOP features from Simula67 Programming language.
  5. A function is a minimum requirement for a C++ program to run.(at least main() function)

Rated as one of the most sought after skills in the industry, own the basics of coding with our C++ STL Course and master the very concepts by intense problem-solving.