Wednesday, November 17, 2010

Conversion of macros into String literals

The # preprocessor operator converts the argument that follows it into a string literal. The preprocessor operator # can be used only in a function-like macro definition.

#include <stdio.h>

#define PRINT(name) printf("The value of " #name " is %d\n", name)

main()
{
 int abc = 100;

 PRINT(abc);
}
Output: The value of abc is 100
Macro Expansion
--> printf("The value of " #name " is %d\n", name)
--> printf("The value of " "abc" " is %d\n", 100)
--> printf("The value of abc is %d\n", 100)
The unary # operator produces a string from its operand. Adjacent string literals are getting concatenated in above example. If the operand to # contains double quotes or escape sequences, they are also expanded.
Similarly ## operator concatenate two tokens passed in macro to a single token.

#define JOIN(a,b)  a ## b
main()
{
   int myname = 100;
   printf("%d", JOIN(my,name));
}
It will be converted into printf("%d", myname);

Thursday, September 16, 2010

Perl System Routines: Functions for process

exec: abandon this program to run another

exit: exits from program


fork: creates new process just like this

getppid: get parent process ID

getpriority: returns current priority of the process

kill: sends a signal to a process or group of process

setpriority:

sleep:

syscall:

system:

times:

wait:

waitpid:

warn:

unlink in Perl: to delete the file

Unlink : this command permanently deletes a list of file from system.
Return: returns number of files successfully deleted. on failure sets value of "$!"  and returns false. It will not tell you the name of file which it couldn't delete.
Do not try deleting directory instead use rmdir command.

unlink("file1.txt");
unlink "a.txt", "b.txt";
unlink @list;
unlink glob "*.bak";

chmod in perl: setting file permissions

Changes the permission of the specified list of files. First argument should be numerical octal value. Returns number of files successfully changed.

usage is as follow:

$result = chmod 0777, "file1.txt","file2.txt";
chmod 0755, @filelist;
$mode  = 0655; chmod $mode, @filelist;

$mode = "0655"; chmod oct($mode), @filelist;
$mode = "0655"; chmod $mode, @filelist; # Not a good usage Should avoid, instead use above method

How to decide mode octal value:
mode is of 4 octal digits e.g. 0754, equivalent to (userID)(user)(group)(Other)
0755: u: full, GO: read and execute
0777: all : full permission
0555: all : read and execute

 symbolic representation of file permissions:

Representation
Class
Description
u
User
Owner
g
Group
Members of file group
o
Others
Neither owner nor group
a
All
Everyone

Octal notation:

Octal
System
Description
0
---
No permission
1
--x
execute
2
-w-
write
3
-wx
Write and execute
4
r--
Read
5
r-x
Read and execute
6
rw-
Read and write
7
rwx
Read, write and execute

link in perl

create a new file linked to oldfile. function creates a hard link if you want symbolic link then use symlink function.
returns 1 on success and 0 on failure. NewFile should not be present else will throw an error. This feature is similar to copying and renaming the file.

link OLDFILE, NEWFILE;
link "file1.txt", "file3.txt";

Perl File operations: Functions for file handling and interacting with system

chdir(EXPR): changes the working directory to EXPR, if EXPR is omitted then changes to home directory. refer to chdir in perl for more details.

chmod: changes the permission on a list of files.

glob:expand filenames using wild card

link: create a hard link in the system

lstat: stat a symbolic link

mkdir: makes a directory, similar to md dos command

opendir: opens a directory in code and gives directory handle.

readlink: determines where a symbolic link is pointing

rename: change a filename

unlink: deletes a file permanently

setting mode permission from command line

type following command in command prompt.
chmod {mode} filename, file2, file3

In C language its used as:
int chmod(const char *File_path, mode_t mode_value);

How to decide mode octal value:
mode is of 4 octal digits e.g. 0754, equivalent to (userID)(user)(group)(Other)

0755: u: full, GO: read and execute

0777: all : full permission

0555: all : read and execute


 symbolic representation of file permissions:

Representation
Class
Description
u
User
Owner
g
Group
Members of file group
o
Others
Neither owner nor group
a
All
Everyone

Octal notation:

Octal
System
Description
0
---
No permission
1
--x
execute
2
-w-
write
3
-wx
Write and execute
4
r--
Read
5
r-x
Read and execute
6
rw-
Read and write
7
rwx
Read, write and execute

These octal values are decided based on binary position of R W X.
R W X
0  0  0
0  0  1 : execute
0  1  0 : Write
1  0  0 : Read

Ex: changing permission for files in whole directory recursively as read, write, execute
chmod -R -v 777 ./*

reference: chmod

Tuesday, September 14, 2010

chdir in perl for changing working directory

usage:
chdir EXPR
chdir(EXPR)

Changes the working directory to EXPR, if possible. If EXPR is omitted, changes to directory specified by $ENV{HOME}, if not set, changes to $ENV{LOGDIR} directory . if none of these is set then does nothing.

Returns 1 upon success, 0 otherwise.
Example:
chdir("C:\temp\working_dir\");

Using file copy and move in perl

copy function is used for copying a file from one location to another. Its present in File::copy module.
 
use File::Copy; 
copy("C:\temp\file1", "C:\tmp\file1.orig") or die "copy failed: $!";  # will make a copy of file1
copy("C:\temp\Fileout.txt", *STDOUT) or die "copy failed: $!";  # will print Fileout.txt into STDOUT
move("C:\temp\Fileout.txt", "C:\temp2\Fileout.txt") or die "move failed: $!";    # will move first argument to 2nd argument

This doesnt support features like creating backups of file, recursive copying etc. these functions also support file handles as argument.

Friday, August 13, 2010

Converting POD To html ( Plain Old Documentation to HTML Conversion)

First you should know what is POD, so for Writing Documentation in Perl Modules Check Article "Plain OLD Documentation". After reading this article you will know what is POD and then point comes to convert it to distributable format i.e. html format, so no one will have to look into your perl code and one can know what all is there in that particular module.

There is a module in Perl Called as "pod2html" which gives details on how to convert pod to html.
 Following is the command line for converting pod 2 html :

 pod2html --help --htmlroot= --infile=
                           --outfile=  --podpath=:...:
                           --podroot= --libpods=:...:
                           --recurse --norecurse --verbos
                           --index --noindex --title=

--htmlroot: Root path when creating HTML File from pod.
--infile: Specify the pod file name to convert to html 
--outfile: HTML Filename to be created, if not given then output will go to STDOUT
--index : Creates index at TOP of HTML File (Default)
--noindex: Oppsite of "--index", don't create index at top
--recurse: Recurse into subdirectories specified in podpath(default)
--norecurse: Do not recurse
--title: Title of resulting HTML File
--verbose: Display progress messages
--podroot: Base directory for finding library pods



Example: pod2html --infile=Test.pm --outfile=Test.html --header --index --backlink="Go Back to Top"

 For further study: POD::HTMLPlain OLD Documentation



Friday, July 30, 2010

Replacing ^M character at end of line using VI editor ( ^H, ^G and so on..)

Some time these characters are placed when you convert file from DOS format to Linux format. These characters can be viewed only with Vi editor or either typing "cat -v" command for that file in command prompt. These characters are called control characters.

These characters can be deleted using ":%s/.$//g" command from VI prompt.
To replace character use it like ":%s/.$/replace/g" Press Ctrl Q+M, and this will character will come up. In some other format it can be typed using ctrl V+M.

But before doing all this do ":set ff=dos", to change file format to DOS.

At last a simple trick for Gvim on Windows XP:
:%s/\r/\r/g
This replaces unix carriage return by windows CRLF.

following is the list of Ctrl characters:

Hex Name
0x00 NUL
0x01 SOH, Control-A
0x02 STX, Control-B
0x03 ETX, Control-C
0x04 EOT, Control-D
0x05 ENQ, Control-E
0x06 ACK, Control-F
0x07 BEL, Control-G
0x08 BS, backspace, Control-H
0x09 HT, tab, Control-I
0x0a LF, line feed, newline, Control-J
0x0b VT, Control-K
0x0c FF, form feed, NP, Control-L
0x0d CR, carriage return, Control-M
0x0e SO, Control-N
0x0f SI, Control-O
0x10 DLE, Control-P
0x11 DC1, XON, Control-Q
0x12 DC2, Control-R
0x13 DC3, XOFF, Control-S
0x14 DC4, Control-T
0x15 NAK, Control-U
0x16 SYN, Control-V
0x17 ETB, Control-W
0x18 CAN, Control-X
0x19 EM, Control-Y
0x1a SUB, Control-Z

Thursday, July 15, 2010

Searching and replacing in VIM

Vim has a command ":s(substitute)" for search and replace text. It searches for text and replace the text.

:%s/abc/xyz/g 
Find each occurrence of 'abc', and replace it with 'xyz'.


:%s/\<abc\>/xyz/gc 
Change only whole words exactly matching 'abc' to 'xyz'; ask for confirmation.

:%s/abc/xyz/gci
Change each 'abc' (case insensitive) to 'xyz'; ask for confirmation.

:%s/abc/xyz/gcI 
Change each 'abc' (case sensitive) to 'xyz'; ask for confirmation.

:s/abc/xyz/g
Replaces in current line only
 :%s/abc/xyz/g
Replaces in all lines
:4,8s/abc/xyz/g
Replaces all abc by xyz in lines between 4 & 8


So ":%s" is equivalent to ":1,$s"

Modifiers:
g: GLobal
c: confirmation
i: case insensitive
I: Case sensitive

Reference: VIM Wiki

Saturday, July 10, 2010

Get more detailed Info on your computer

Hi,
I know you want to know details about your computer's directx componets and their drivers are installed, and what they are using. this tool lets you diagnose problems and change your system settings to best. So to check more detailed info on your computer, which is not even available on My computer->Properties section, Follow the steps:
1. Open RUN Prompt.
2. type dxdiag and enter
3. Make sure you have original version version of XP because it will propmt for that.
4. Once it opens up it will show information on : System, DirectsX Files, Music, Display, Sound, Input devices etc..
5. To save this info click on "Save all information" and select the location. Information will be saved in form of .txt file.

Creating folder wothout any name

you will be wondering, how to create a folder without any name.. Have you ever tried it?? If no then try it now..

Here is the solution for this..
1. Create a folder in any directory.
2. Right click on folder and select "Rename folder" or press F2
3. Now press Alt and Type 255(ALT+255) or ALT+0160
4. Now it's done.

Monday, June 28, 2010

Turning OFF Autoplay on All Drives using Group Policy

To disable Auto play of External Drives or Internal Drives or removable Disks please follow steps below mentioned. It's actually useful to disable Auto Play so that you will not get affected by any kind of virus which gets transfered via PenDrives or external drives. Also will avoid attack of autorun.inf virus.

  • Click on Start and open run.
  • Now type gpedit.msc, and Enter.
  • Now go to "User Configuration" -> "Administrative templates" -> "System" -> "Turn Off Autoplay"
  • Now select Enable and Select "turnoff autoplay on 'All Drives' ".
  • Select OK and Now you are Done!! 
Check This Link for details on how to remove autorun.inf virus

    Monday, June 14, 2010

    Restoring mozilla's bookmarks

    Firefox 3 no longer uses bookmarks.html to store the bookmarks. It stores the bookmarks and the browser history in places.sqlite and no longer creates a HTML backup by default instead there are also JSON backups in the bookmarkbackups folder within the Firefox profile folder.
    Check for backups in following path : 
    C:\Documents and Settings\<User Name>\Application Data\Mozilla\Firefox\Profiles\<some  folder>\bookmarkbackups


    See Lost_Bookmarks (MozillaZine KB)
    You can export the bookmarks in Firefox to a HTML file: Bookmarks > Organize Bookmarks > Import & Backup > Export HTML
    You can also create a JSON backup: Bookmarks > Organize Bookmarks > Import & Backup > Backup

    If migrating to new account , then just copy the latest JSON file to new account's bookmarkbackup folder and restore it in mozilla.
    You should restore a JSON backup: Bookmarks > Organize Bookmarks > Import & Backup > Restore-> Choose file
     Restoring a JSON backup will replace all existing bookmarks. You can merge bookmarks if you import a HTML backup.

    A HTML backup doesn't support tags and annotations, so if you want to preserve those then you need to use a JSON backup.

    Wednesday, June 9, 2010

    How to remove autorun virus from Hard disk or How to open HDD by double click

    Some time you are not able to open your hard disk drives(HDD) by double clicking, so to enable that please follow following procedures:
    > open command prompt
    > type and enter "cd\", this will take you to the root of C: Drive
    > type "attrib -h -r -s autorun.inf" and enter
    > now type and enter "del autorun.inf" to delete autrun.inf file
    > Similarly follow same steps for all the drives and then restart your computer
    > Same steps can also be followed for pendrives or removable media.

    > Now just enjoy the freedom of double clicking.

    Tuesday, June 8, 2010

    Getting Information about file

    File Checking
    Existence:


    if( -e $file) { print "File exists \n";}
    else { print "File doesn't exist\n"; }

    File exists with size 0(zero) : -z
    File exists with size non-zero : -s

    Readable/writable/Executable

    File Readable : -rFile Writable : -w
    File Executable : -x

    Text/Binary

    Text : -T
    Binary : -B

    Tuesday, May 11, 2010

    Enabling Task Managaer disabled by Virus

    Method 1:
    > Open Run window and type gpedit.msc and click ENTER.
    > Now Goto location: User Configurations/Administrative Templates/System/Ctrl+Alt+Del Options

    > Double click on Remove Task Manager on right side Pane. And select the value as "Not Configured" as follow.

    Method 2:
    > start "RUN" Window and type regedit and Enter
    > GoTo this registry index: HKEY_CURRENT_USER \ Software \ Microsoft \ Windows \ CurrentVersion \ Policies\ System
    > In the right pane, find and delete the value named as DisableTaskMgr 
    > Close  Registry Editor

    Thursday, April 22, 2010

    BEGIN, INIT, CHECK, UNITCHECK, END : Five different code blocks

    These are different types of code blocks available in Perl, which get executed during start and end of any Perl program. One can have more than one of these blocks in any Perl program, and will get executed in appropriate moment.

    BEGIN: It gets executed in Compile time, as soon as possible, even before the rest of the file is parsed. There may be multiple BEGIN{} blocks and they will be executed in FIFO.

    END : It is executed as late as possible, that is, after Perl has finished running the program and just before the interpreter is being exited, even if it is exiting as a result of a die() function. There may be multiple END{} Blocks, within a file. They will be executed in LIFO(reverse) order. END blocks are not executed when you run Perl with -c switch i.e. It's not called in compile time.

    UNITCHECK: It's called after the unit which defined them has been compiled. The main program file and module it loads are compilation units.

    CHECK: These are run just after initial compile phase ends and before the run time begins in LIFO order. These are used by Perl compile suite to save the compiled state of the program.

    INIT : These are run just before Perl run time begins execution in FIFO Order.

    INIT, CHECK, UNITCHECK, blocks are used to catch the transition between compilation phase and execution phase of main program.
    ##########################################################
    # One example program for Perl mod
    print "8. Ordinary code runs at runtime.\n";

     END { print "12. Read perlmod for the rest of the story.\n" }
     INIT { print " 6. INIT blocks run FIFO just before runtime.\n" }
     UNITCHECK { print " 4. And therefore before any CHECK blocks.\n" }

     print "9. It runs in order, of course.\n";

     BEGIN { print " 1. BEGIN blocks run FIFO during compilation.\n" }
     CHECK { print " 5. CHECK blocks run LIFO after all compilation.\n" }
     BEGIN { print " 2. So this line comes out second.\n" }
     INIT { print " 7. Run this again, using Perl's -c switch.\n" }
     END { print "11. END blocks run LIFO at quitting time.\n" }
     UNITCHECK { print " 3. UNITCHECK blocks run LIFO after each file is compiled.\n" }

     print "10. It merely _looks_ like it should be confusing.\n";

    Wednesday, April 7, 2010

    including/Using/Require Perl Modules in Program

    There are many ways to include modules/packages in your program.

    Use Module;

    Or
    Use Module List;

    Which is exactly equivalent to

        BEGIN { require Module; import module; }
                       or
        BEGIN { require Module; import Module List; }
                       or
        require "Module.pm";
        import Module;

    All perl modules have extensions.pm, use assumes this so you don't have to spell it out explicitly as "Modules.pm" instead you can say use Module;

    Following two statements:

    require Module;
    require "Module.pm";

    differ from each other. In first case, any double colon ( my::module) will be translated to  system's directory separator e.g."/", while in second case you will have to give module name with path literally.


    With "require" one can get into following problem:
    require myModule;
    $some = myModule::somefunc();  # Need to make myModule:: accessible

    use myModule;               # Import Names from myModule
    $some = somefunc();

    require myModule;
    $some=somefunc();  # Error: No main::somefunc(),    so be careful in this case. solution is as follow

    Above problem can be solved as following:
    require "myModule.pm";
    import myModule;
    $some=somefunc();

    Command Line inclusion
    For including module from command line use following command:
    C:\>perl -MmyModule myprogram.pl

    For more information on -M switch check perlrun in perldoc
    For more information on this refer to this link.
    or check in chapter 11. modules in Perl Programming.

    Monday, March 29, 2010

    Perl Functions & Keywords : a summary

    Here are Perl's functions (including things that look like functions, like some keywords and named operators). Some functions may appear in more than one place just because they can be categorize in more than one place.

    SCALARs or strings Functions:

    chomp, chop, chr, crypt, hex, index, lc, lcfirst, length, oct, ord, pack, q//, qq//, reverse, rindex, sprintf, substr, tr///, uc, ucfirst, y///

    Regular expressions and pattern matching Functions

    m//, pos, quotemeta, s///, split, study, qr//, tr///

    Numeric functions

    abs, atan2, cos, exp, hex, int, log, oct, rand, sin, sqrt, srand

    Functions for real @ARRAYs

    pop, push, shift, splice, unshift

    Functions for list data

    grep, join, map, qw//, reverse, sort, unpack

    Functions for real %HASHes

    delete, each, exists, keys, values

    Input and output functions
    binmode, close, closedir, dbmclose, dbmopen, die, eof, fileno, flock, format, getc, print, printf, read, readdir, rewinddir, say, seek, seekdir, select, syscall, sysread, sysseek, syswrite, tell, telldir, truncate, warn, write

    Functions for fixed length data or records

    pack, read, syscall, sysread, syswrite, unpack, vec

    Functions for filehandles, files, or directories

    -X, chdir, chmod, chown, chroot, fcntl, glob, ioctl, link, lstat, mkdir, open, opendir, readlink, rename, rmdir, stat, symlink, sysopen, umask, unlink, utime, mkpath


    Miscellaneous functions

    defined, dump, eval, formline, local, my, our, reset, scalar, state, undef, wantarray

    Functions for processes and process groups
    alarm, exec, fork, getpgrp, getppid, getpriority, kill, pipe, qx//, setpgrp, setpriority, sleep, system, times, wait, waitpid

    Low-level socket functions

    accept, bind, connect, getpeername, getsockname, getsockopt, listen, recv, send, setsockopt, shutdown, socket, socketpair

    System V interprocess communication functions

    msgctl, msgget, msgrcv, msgsnd, semctl, semget, semop, shmctl, shmget, shmread, shmwrite

    Fetching user and group info

    endgrent, endhostent, endnetent, endpwent, getgrent, getgrgid, getgrnam, getlogin, getpwent, getpwnam, getpwuid, setgrent, setpwent

    Fetching network info

    endprotoent, endservent, gethostbyaddr, gethostbyname, gethostent, getnetbyaddr, getnetbyname, getnetent, getprotobyname, getprotobynumber, getprotoent, getservbyname, getservbyport, getservent, sethostent, setnetent, setprotoent, setservent

    Time-related functions

    gmtime, localtime, time, times

    Keywords related to the control flow of your Perl program
    caller, continue, die, do, dump, eval, exit, goto, last, next, redo, return, sub, wantarray

    Keywords related to switch
    break, continue, given, when, default

    (These are only available if you enable the "switch" feature. See feature and "Switch statements" in perlsyn.)

    Keywords related to scoping
    caller, import, local, my, our, state, package, use
    (state is only available if the "state" feature is enabled. See feature.)
     
    Keywords related to perl modules
    do, import, no, package, require, use

    Keywords related to classes and object-orientation
    bless, dbmclose, dbmopen, package, ref, tie, tied, untie, use

    Functions new in perl5

    abs, bless, break, chomp, chr, continue, default, exists, formline, given, glob, import, lc, lcfirst, lock, map, my, no, our, prototype, qr//, qw//, qx//, readline, readpipe, ref, sub*, sysopen, tie, tied, uc, ucfirst, untie, use, when

    * - sub was a keyword in perl4, but in perl5 it is an operator, which can be used in expressions.

    Functions obsoleted in perl5

    dbmclose, dbmopen

    For more information on Perl Function Check this link