Print Upside Down

From one of the forums i was reading i got the idea of creating this program.Inputs some line of text and prints them as it was traversed from up to down when arranged in a row-column like structure.

Sample Input:-

ABCD
BMNF

Output:-

ABBMCNDF

#include <stdio.h>
#include <string.h>
#define BYTES 512

void pud(char *p,int o)
{
    if(!*p)return;
    int len=strlen(p);
    if(len>o)
        putchar(*(p+o));
    while(*p++);        /*points to first character of the next line*/
    pud(p,o);
}

int main()
{
    char str[BYTES];
    int i,max=0x0,j=0x0,t,size;
    
    size=fread(str,1,BYTES - 0x1,stdin);
    str[size]='\x00';
    
    for(i=0x0;i<size;i++){
         if(str[i]=='\n'){
             str[i]='\x00'; /*to make it usable by strlen*/
             t=strlen(&str[j]);
             if(t>max)
                 max=t;
             j=i + 0x1;
             }
    }

    for(i=0x0;i<max;i++)
        pud(str,i);
        
    return 0x0;
}

Cat

Another minimal implementation of cat.The gnu cat implementation read the file in the dynamically allocated buffer by using the formula (OUTSIZE – 1 + INSIZE * 4 + LINE_COUNTER_BUF_LEN).As you can see the buffer allocated is very large when compared to file.If the file is hugeeee then it can create problem on a low memory machine.So i thought i should create a cat implementation which reads the file in chunks in a fixed size buffer rather than whole file at once.At the first sight it looked easy but it had to care of previous and upcoming states to determine its output!
Here is my mini cat.Supported command options:-
-n //number all output lines
-b //number non-blank output lines
-t //display tabs as ^I
-e //display end-of-line characters as $

Mini Cat:-

#include <stdio.h>
#include <string.h>
#define  ISFTAB(x) x=='\t' || x=='\n'                 /*Non-printable characters format tags*/

enum{OPT_N=0x8,OPT_E=0x4,OPT_B=0x2,OPT_T=0x1};
enum{NEWF,TABF};                                      /*You can add more format tags(for non-print chars) here*/
int lcount=1;

/*Get's the next line from the input stream*/
int getline(char *buff,int max,FILE *fp)
{
    if(fgets(buff,max,fp)==0)
      return 0;
    return strlen(buff);
}

/*Returns the format tag for the non printable character*,it is extensible*/
char *fnonprint(char *f,char c)
{
    static char ftab[][5]={"$\n","^I"};
    int t=-1;
    if(c=='\n')
      t=NEWF;
    else if(c=='\t')
      t=TABF;
    return strcpy(f,ftab[t]);
}

void cat(const char *in,int opt)
{
    const char *p=in;
    char fc[10];
    if(*p=='\n'){
        if(opt&OPT_N)
          fprintf(stdout,"%d.",lcount++);
        if(opt&OPT_E)
          fprintf(stdout,"%s",fnonprint(fc,'\n'));
        else
          putchar('\n');
        return;                     /*The line is empty so no need of further processing and return*/
    }
    if(opt&OPT_N || opt&OPT_B)
      fprintf(stdout,"%d.",lcount++);       /*-b and -n option is to print line number for non-blank and all lines,both of which is
                                    true here because non empty line has been checked before*/

    while(*p){
        if(ISFTAB(*p)){
          if(opt&OPT_E || opt&OPT_T)
            fprintf(stdout,"%s",fnonprint(fc,*p));
          else
            putchar(*p);
        }
          else
            putchar(*p);
        p++;
    }
}

int main(int argc,char *argv[])
{
    int nfiles=0;
    int opt=0,i=0;
    FILE *fp;
    char in[512],c;

    while((++argv)[0] && argv[0][0]=='-'){
        while(c=*++argv[0])
            switch(c){
                case 'e':
                 opt|=OPT_E;
                 break;
                case 'b':
                 opt|=OPT_B;
                 break;
                case 't':
                 opt|=OPT_T;
                 break;
                case 'n':
                 opt|=OPT_N;
                 break;
                default:
                 fprintf(stderr,"cat:Unknown option %c",c);
                 return 1;
            }
    }

    while(argv[0]){
        nfiles++;
        fp=fopen(argv[0],"r");
        if(!fp){
          fprintf(stderr,"cat:Unable to open file %s",argv[0]);
          return 1;
        }
        while(i=getline(in,sizeof in,fp))
             cat(in,opt);

        fclose(fp);
        argv++;
    }
      /*take input from stdin*/
     if(nfiles==0){
        fp=stdin;
        while(i=getline(in,sizeof in,fp))
             cat(in,opt);
    }
    return 0;
}

String Replace

This  program removes all occurence of argv[1] by argv[2] in the file argv[3].

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

/* Return the length of the file.Paramter is the file descriptor of the file */
off_t filelength(int fildes)
{
 off_t filesize;
 filesize=lseek(fildes,0,SEEK_END);
 lseek(fildes,0,SEEK_SET);
 return filesize;
}

/* Finds needle in p and if found skips needle string and print replace */
void match(char *p,const char *needle,const char *replace,size_t size)
{
 char *t;
 char *begin;
 char *c;
 int  needle_len;
 t=p ;    /* t is the current position of the buffer */
 begin=p; /* begin always point to the character from where printing starts */
 needle_len=strlen(needle);
 for(;(t-p)!=size;){

 t=strstr(t,needle);
 if(t){
 for(c=begin;c!=t;c++)/* t contains the address of needle so skip it */
 putchar(*c);
 printf("%s",replace);/* Prints replace in place of the needle string */
 t+=needle_len;       /* t now pints to the string after the match */
 begin=t;             /* Update begin to print from the charatcers after the match */
 }
 else break;
 }
 /* Prints the remaining character in the buffer which has no match with needle */
 for(c=begin;(c-p)!=size;c++)
 putchar(*c);
 //putchar('\n');
}

int main(int argc,char *argv[])
{
 if(argc!=4 && argc){
 fprintf(stderr,"Illegal number of parameters\n");
 return 1;
 }
 else
 if(argc==1){
 printf("Usage %s <string_to_replace> <string_to_replace_by>\n",argv[0]);
 return 1;
 }

 int fd;
 off_t size;
 char *chunk;
 char *needle;
 char *replace;

 needle=argv[1];  /*String to replace */
 replace=argv[2]; /*String to replace needle by */

 if((fd=open(argv[3],O_RDONLY))==-1){
 fputs("Error in opening file",stderr);
 return 1;
 }
 size=filelength(fd);
 chunk=(char*)malloc(size+1);
 if(!chunk){
 fputs("Memory intialization failure",stderr);
 return 1;
 }

 if(read(fd,chunk,size)==size)
 match(chunk,needle,replace,size);
 else {
 fputs("Error in reading file\n",stderr);
 return 1;
 }
 return 0;
}

Word Sort

This C program sorts all the word in the file supplied as argument lexicographically.The getword() function gets the next word and the bst_insert() function inserts it in the tree.The approach here used is that of Binary Search Tree.After this all it traverses the tree in inorder method and prints it to the console,each word in a new line.Suppose that if the word is there in the file more tahn 1 time then it is displayed that much time on the line each time separated by spaces.

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

char *pos;               /*position of the pointer in the buffer*/
char *word;             /*pointer to word scanned by getword()*/
int str_val;

struct pWord
{
char *pw;                  /*pointer to the word */
size_t w_count;         /*count of the word in the file */
struct pWord *left;
struct pWord *right;
};

/*Get's the next word from the buffer*/

void getword()
{
char *w=pos;
word=w;
if(!isalnum(*w)){
if(*w!=EOF){
*w='\x00';
pos++;
}
return;
}

 while(isalnum(*w=*pos++))w++;
*w='\x00';
pos=w+1;
}

struct pWord * bst_insert(struct pWord * wp,char *str)
{
if(wp=='\x00'){
wp=(struct pWord*)malloc(sizeof(struct pWord));
wp->pw=str;
wp->left=wp->right='\x00';
wp->w_count=1;
return wp;
}

 str_val=strcmp(str,wp->pw);
if(str_val < 0)         wp->left=bst_insert(wp->left,str);
else if(str_val> 0)
wp->right=bst_insert(wp->right,str);
else
wp->w_count++;
return wp;
}

void print_word(struct pWord * wp)
{
while(wp->w_count--){
fputs(wp->pw,stdout);
putchar(wp->w_count==0 ? '\n' : ' ');
}
}

void inorder(struct pWord *wp)
{
if(wp!='\x00'){
inorder(wp->left);
print_word(wp);
inorder(wp->right);
}
}

long int filelength(FILE *fp)
{
long int size;
fseek(fp,0,SEEK_END);
size=ftell(fp);
rewind(fp);
return size;
}

int main(int argc,char *argv[])
{
if(argc!=2){
fputs("Invalid arguments\n",stderr);
exit(1);
}

FILE *fp=fopen(argv[1],"r");
long int size=filelength(fp);

 if(size==-1){
fputs("Error in initializing:Calculating file length\n",stderr);
exit(2);
}

char *buff=(char*)malloc(size+1);
if(buff=='\x00'){
fputs("Error in memory allocation:Memory maybe low\n",stderr);
exit(3);
}

 if(fread(buff,1,size,fp)!=size){
fputs("Error in reading file:File may be in use by other process\n",stderr);
free(buff);
exit(4);
}

buff[size]=EOF;
pos=buff;

struct pWord *wp='\x00';
getword();
while(*word!=EOF){
if(*word!='\x00')
wp=bst_insert(wp,word);
getword();
}
inorder(wp);
free(buff);
return EXIT_SUCCESS;
}

IRC Praser

IRC stands for Internet Relay Chat.There are many irc clients/bots out there and the heart of them is the irc parser which works according to the irc protocol.This Java program is a simple one,which reads raw irc log file “raw.log” and parses each line of command and place its parts in the IrcMsg class which is like a nested structure.

/*
 * IRC Parser by Warrior in compliance with RFC1459.
 * If you plan to use this source code or part of it then you will have to
 * agree to the following License.
 * License:- http://creativecommons.org/licenses/by/2.5/in/
 * You will have to give the author credit on using part or full of this
 * source code.
 */

import java.io.*;

class IRC{
 static IrcMsg irc_msg=new IrcMsg();
 static IrcParser irc_parser=new IrcParser(irc_msg);

 public static void  display(){
 System.out.print(irc_msg.prefix.nick+" "+irc_msg.cmd.num_reply+":"
 +irc_msg.cmd.command+"\n");

 for(int i=0;i<irc_msg.param_cnt;i++)
 System.out.print(irc_msg.params[i]);

 System.out.print("\nUser:"+irc_msg.prefix.user+" Host:"+irc_msg.prefix.host+"\n");
 }

 public static void main(String args[])throws IOException{
 GetData lget=new GetData("raw.log");
 String line;
 while((line=lget.getline())!=null){
 //System.out.println("Raw:-"+line);
 irc_parser.irc_scan(line);
 display();
 }
 }
}

//You can substitute this class to get data from irc server
class GetData{
 String log;
 FileReader file;
 BufferedReader fin;
 GetData(String name){
 log=name;
 try{
 file=new FileReader(log);
 fin=new BufferedReader(file);
 }catch(FileNotFoundException e){
 System.out.println("File not found:"+e);
 System.exit(1);
 }
 }

 String getline()throws IOException{
 char c;
 String line;
 line=fin.readLine();
 if(line==null)
 fin.close();
 return line;
 }
}

//Idea is to create a skeleton like nested structures
class IrcMsg{
 static Prefix  prefix;
 static Command cmd;

 IrcMsg()
 {
 prefix=new Prefix();
 cmd=new Command();
 }

 class Prefix{
 String nick;
 String user;
 String host;
 }

 class Command{
 String command;
 int num_reply;
 }

 static String params[]=new String[15];
 static int param_cnt;
}

class IrcParser{
 static IrcMsg irc_msg;

 IrcParser(IrcMsg irc_msg){
 this.irc_msg=irc_msg;
 }

 boolean irc_number(char c){
 return (c>='0' && c<='9');
 }

 boolean irc_letter(char c){
 return ((c>='A' && c<='Z')||(c>='a' && c<='z'));
 }

 boolean irc_trail(char c){
 return (c==':');
 }

 boolean irc_special(char c){
 return ("-[]\\`^{}".indexOf(c)!=-1);
 }

 boolean irc_user(char c){
 return ("@\r\n".indexOf(c)==-1);
 }

 boolean irc_host(char c){
 return (irc_letter(c) || irc_number(c) || c=='.' || c=='-');
 }

 boolean irc_space(char c){
 return (c==' ');
 }

 boolean irc_eol(char c){ //irc commands are generally terminated by CRLF
 return (c=='\r' || c=='\n');
 }

 void    zeromemory(){
 for(int i=0;i<15;i++)
 irc_msg.params[i]="";
 irc_msg.param_cnt=0;
 irc_msg.prefix.nick="";
 irc_msg.prefix.user="";
 irc_msg.prefix.host="";
 irc_msg.cmd.command="";
 irc_msg.cmd.num_reply=0;
 }

 boolean irc_scan(String irc_str){
 String msg=irc_str;
 String tmp="";
 char c=0;
 int  i=0;
 int  n=0;
 int  pcnt=0;
 int  ncnt=0;
 int  t;
 int len=msg.length();

 zeromemory();
 if(irc_trail(msg.charAt(0))){
 for(i=1;i<len;i++){
 c=msg.charAt(i);
 if(!irc_number(c) && !irc_special(c) && !irc_letter(c) &&!irc_host(c))
 break;
 tmp=tmp+c;
 }

 irc_msg.prefix.nick=tmp;
 //System.out.println("Prefix:"+tmp);
 tmp="";

 if(c=='!'){
 for(++i;i<len;i++){
 c=msg.charAt(i);
 if(!irc_user(c))break;
 tmp=tmp+c;
 }
 irc_msg.prefix.user=tmp;
 //System.out.println("User:"+tmp);
 tmp="";
 }

 if(c=='@'){
 for(++i;i<len;i++){
 c=msg.charAt(i);
 if(!irc_host(c))break;
 tmp=tmp+c;
 }
 irc_msg.prefix.host=tmp;
 //System.out.println("Host:"+irc_msg.prefix.host);
 tmp="";
 }

 while(irc_space(msg.charAt(i)))i++;
 }

 tmp="";
 for(;i<len;i++){
 c=msg.charAt(i);
 if(!irc_letter(c) && !irc_number(c))
 break;
 if(irc_number(c))n=1;
 tmp=tmp+c;
 ncnt++;
 }

 if(n==1 && ncnt==3)//the numeric reply of server is only 3 digits long
 irc_msg.cmd.num_reply=Integer.parseInt(tmp);
 else
 irc_msg.cmd.command=tmp;
 //System.out.println("Command:"+irc_msg.cmd.command);
 if(irc_space(c) && i<len)c=msg.charAt(++i);
 tmp="";

 for(;i<len;i++,pcnt++){
 c=msg.charAt(i);
 /*Trailing parameters can contain spaces..so break if it is a
 * ':' character and continue to the next segment for handling : characters
 * to eat all spaces in a single string variable
 */
 if(irc_eol(c) || irc_trail(c))break;
 t=i;
 while(i<len && !irc_space(msg.charAt(i))) i++;
 if(i>=len)break;

 irc_msg.params[pcnt]=msg.substring(t,i);
 }

 if(irc_trail(c)){
 for(i++;i<len;i++){
 c=msg.charAt(i);
 if(irc_eol(c))break;
 tmp=tmp+c;
 }
 irc_msg.params[pcnt++]=tmp;
 }

 irc_msg.param_cnt=pcnt;
 //for(i=0;i<pcnt;i++)
 //System.out.println("params["+i+"]:"+irc_msg.params[i]);
 return true;
 }
}

//Report Bugs at this thread.

Portscanner

Hello there,This is a very simple portscanner which takes the site name as argument and use the brute force to scan for open port.

/*
This porogram finds the port number a server connects to.In Dev-C++ while compiling a link
error can crept in.It can be resolved;Goto Project>Project Options>Parameters>>linker and
add "-lws2_32"
*/

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

int main(int argc,char *argv[])
{
 int iResult,port_num;
 WSADATA wsaData;
 if(argc!=2){
 printf("Usage: %s <sitename>", argv[0]);
 return 1;
 }
 iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
 if (iResult != NO_ERROR){
 printf("Error at WSAStartup()");
 return 1;
 }

 SOCKET ConnectSocket;
 ConnectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
 if (ConnectSocket == INVALID_SOCKET) {
 printf("Socket Intialization error!");
 WSACleanup();
 }

 HOSTENT *he;
 sockaddr_in clientService;
 clientService.sin_family = AF_INET;
 he=gethostbyname(argv[1]);
 clientService.sin_addr.s_addr =*((unsigned long*)he->h_addr);//The IP Address of the server to be connected
 printf("Now scanning for open port on %s\n",argv[1]);
for(port_num=0;port_num<65536;port_num++)
{
clientService.sin_port = htons( port_num ); //Updates the port number
printf("\rScanning Port: %d",port_num);
if ( connect( ConnectSocket, (SOCKADDR*) &clientService, sizeof(clientService) ) != SOCKET_ERROR)/*Tries to connect on the port value specified by i*/ {
printf("\nConnected to %s on port %d",argv[1],port_num);
break;
}
}
WSACleanup();
return 0;
}