Testing for TRUE and FALSE; A Problem Scenario

I wish they did better fact checking in these textbooks. Here’s a case in the C Programming book I’m reading. I was having problems with the following code:

FILE* spIn;
spIn = fopen("program73.dat", "r");
if(spIn != NULL)
 {
 printf("Could not open file.\a\n");
 exit(101);
 } // if open fails

Here’s the problem. The line if(spIn != NULL) always exits the program. However, if(!spIn) and if(spIn == NULL) both work fine.

The problem is that he was telling the program to terminate if the file opened successfully, the opposite of what he meant. The file pointer returns NULL if it’s not able to open the file. He told the program to exit if the pointer did not return NULL; in other words, the program terminated every time the file opened successfully. The other two checks I used checked to see if NULL was returned and the program would exit only if the file did not open successfully.

In a textbook, I certainly think the author should compile and test his programs to see if they work correctly a greater extent than this. However, this underscores a common problem for programmers. It’s very easy to get your tests backwards when testing for true and false conditions.

The best rule? Keep it simple and readable. If you have to take time to think through the logic, look for an easier way to write the condition. The second best rule, I guess, is to actually compile and run a program before you include it in a book, just to make sure it works correctly.

Dynamically Allocating Memory for an Array

InPursuitYes, I know I haven’t written in a while. I’ve been busy. I decided to go back to college to learn the things I wanted to learn. I would get so far with C, then my eyes would glaze over. So, I’ve been taking 14 hours while working full time, to force myself to learn to code the things my mind typically avoids.

I’m finding that the course material is better for me than the tutorials I find online. One case in point is using malloc to dynamically allocate memory for arrays. This is something I wouldn’t have been able to do before. I’ve been taking C++ at school and it’s making C easier for me to understand. I’m taking the second semester of C++ in the spring, and a C class as well.

Enough of that, let’s create a dynamic array! I’ve taken someone else’s code, that I felt was incomplete, and rewritten it. This program runs fine on Linux. You may want to add #include <conio.h> to the include statements at the beginning if you are using a Microsoft OS.

// first we include the libraries
#include <stdio.h>
#include <stdlib.h>

// everything else, we'll do in main
int main() {
  // declare variables, including
  // array declared as int* array; a pointer
  // initially point it to NULL to avoid potential problems
  // programmers differ on whether the pointer should be type cast
  // a void pointer will return an error if you forget to include
  // the library but type casting makes the code compilable in C++
  int* array = NULL;

  // n will be a user-supplied number
  // i will be used as a counter in the for loop(s)
  int n, i;

  // Ask the user how many elements they want in the array
  printf("Enter the number of elements you want in the array: ");
  scanf("%d", &n);

  // this statement allocates memory for
  // n elements the size of an int
  array = (int*) malloc(n*sizeof(int));

  // check to see if the memory allocation failed
  // if it did, notify the user of the problem
  // and terminate the program with an error
  if(NULL == array)
  {
    puts("\nError allocating memory for array! Terminating!\n");
    return 1;
  }

  // everything's okay, so we'll ask the user to
  // enter a number for each element of the array
  for (i=0; i<n; i++) {
  printf("Enter number %d: ", i);
  scanf("%d", &array[i]);
  }

  // output the array one element at a time
  // then output its size for the user
  printf("\nThe Dynamic Array is: \n");
  for (i=0; i<n; i++) {
  printf("The value of %d is %d\n", i, array[i]);
  }
  printf("Size= %d\n", i);

  // when finished, free the memory that was allocated for the array
  free(array);

  // point the pointer to null
  // so you do not accidentally 
  // try to use it again with
  // unexpected results
  array = NULL;

  // return zero, exiting without errors
  return 0;
}

I thought it pretty strange that one example I saw didn’t show the user how to free the memory after the operation. Also, several didn’t bother setting the array pointer to point at NULL.

Memory is routinely freed once it is no longer in use by the program. If you want your program to run efficiently and cleanly, manually freeing memory that is no longer in use is more than just a good idea. The ability to directly manage memory like this is one of the big reasons to use a lower-level language like C or a mid-level language like C++. Assigning the pointer to NULL after freeing memory assures that you will get an error message if you accidentally try to use the pointer again to access the memory that has been freed.

Speaking of C++, I found the following example of doing the same thing in that language.

// i am not providing the full code here, just snippets

// start by declaring the pointer and initializing it to NULL
// C++ is a strongly typed language, so you must declare the 
// proper type for the array you want to use
int* a = NULL;
  
int n;           // declare the size variable

cin >> n;        // get the size from the user
a = new int[n];  // allocate memory for that number of ints
                 // note the comparative simplicity of the
                 // statement compared to the C statement
// increment through the elements
// put one more than the number of 
// that element in the element 
// will read 1 2 3 ... n when outputting 
for (int i=0; i<n; i++)
{
    a[i] = i+1;
}

// now iterate again, printing each array element
for(int i=0; i<n; i++
{
    cout << a[i] << endl;
}

// finished with the array, now free the memory
delete [] a;

// memory is free, now point the pointer a to NULL
// to prevent accessing the freed memory
a = NULL;

Memory that your program didn’t free will be freed when the program terminates but it’s best to free it manually where appropriate. Never free memory that wasn’t dynamically allocated – the results are unpredictable.

You must specify “[]” when deleting an array, but not for a single value. It isn’t possible
to delete only part of an array. As I mentioned before, setting the pointer to NULL isn’t strictly necessary, but it’s the best practice so that any further use of the pointer will produce an error. Some compilers will take care of that for you when you delete the
pointer but it’s best to do it anyway, just in case.

C Programming – Pointer to argc

InPursuitJust for fun, here’s a little program that uses a pointer to return the number of arguments that are submitted to the program at the command line.

#include <stdio.h>

int main(int argc, char argv[])
{
int *ptrArgc;

ptrArgc = &argc;
printf("\n\nOutput number of arguments in argc: %d \n\n", *ptrArgc);

printf("\n\nOutput memory address of argc: %d \n\n", ptrArgc);

return 0;

}

First, notice the line that declares the main() function in the program. The “int argc” declares an integer that automatically fills itself with the number of arguments entered at the command line when you run the program. The name of the program is the first argument, so the smallest number it can return is 1. The “char argv[]” is a character array that contains all the arguments entered at the command line, with “argv[0]” returning the name of the program itself.

The line “int *ptrArgc;” line declares a pointer and the “ptrArgc = &argc;” line assigns the memory address of argc to the pointer.

When printf() is used for the first time, ptrArgc is dereferenced with an asterisk. This causes it to print the value contained in argc instead of the memory address.

The second time printf() is used, ptrArgc is not dereferenced, so it prints the number actually contained in ptrArgc, which is the memory address that holds the value for argc.

Try compiling and running this program, entering different numbers of arguments at the command line. Notice the assigned memory address changes when you run the program.

C Programming – Binary to Decimal Converter

InPursuit

There are 10 kinds of people in this world, those who understand binary and those who don’t. — Unknown

While reading a book on assembly language programming, I came across a section that discussed different numbering systems used and how to convert from one to another. I gave myself some assignments to complete one at a time. Here’s the first one. This converter takes an 8-bit, unsigned binary number, entered at the command line as argv[1], and converts it to its decimal equivalent.

This was a fun assignment. It can easily be modified to take a 16-bit number instead, simply by changing the number of iterations in the for() loop and the starting number for the myCount variable. It uses the pow() function in math.h but everything else in the code is pretty straight forward. I have not tested it fully but it does compile and work using the Visual Studio 2012 command line compiler.

// function receives a string containing an 8-bit, unsigned binary integer 
// returns the decimal integer value of the binary integer
#include <stdio.h>
#include <string.h>
#include <math.h>
int main(int argc, char *argv[])
{
 const char *binNumber = argv[1];
 int decNumber = 0;
 int myDecCount;
 int myCount = 7;

 puts("\n\nBinary to Decimal Converter\nby David Peterson Harvey\n\n");

if (argc == 2)
 {
 printf("%s converts to %d\n\n", binNumber, decNumber);
 // if argv[1] == 8 digits long, binNumber = {argv[1]};
 if(strlen(argv[1]) == 8)
 {
 for(myDecCount=0; myDecCount <=7; myDecCount++) 
 {
 if(binNumber[myCount] == '1')
 {
 decNumber = decNumber + pow(2, myDecCount);
 }
 printf("\nCurrent number %d.\nCurrent count %d.\n\n", myDecCount, decNumber);
 myCount--;
 }
 }
 else
 {
 printf("You must enter a binary number 8 digits long. You entered %s.\n\n", argv[1]);
 }
 }
 else
 {
 printf("To use program:\n\n\t %s 8-digit_binary_number\n\n", argv[0]);
 }
return 0;
}

C – Temperature Conversion

InPursuit I’ve been having fun, reading through a couple of books. One is the second addition of K&R’s “The C Programming Language,” arguably the standard for the C programming language. Early in the book, they provide the reader with a simple conversion table between Fahrenheit and Celsius. I decided it would be fun to take their code a step further and provide a little more functionality to the program. In my spec, I would have the original table generation available but I would also provide functionality to allow the user to enter his or her own temperatures for conversion. The original table provided a one way conversion then displayed the results in a table so the user could reference the table. I had to provide calculations both ways, from Fahrenheit to Celsius and from Celsius to Fahrenheit.

Here’s the original program.

int main()
{
/* print Fahrenheit-Celsius table
for fahr = 0, 20, ..., 300 */
int fahr, celsius;
int lower, upper, step;

lower = 0;
upper = 300;
step = 20;
fahr = lower;

puts("Conversion Table:\n\n");
while(fahr <= upper)
{
celsius = 5 * (fahr-32) / 9;
printf("%d\t%d\n", fahr, celsius);
fahr = fahr + step;
}
}

Here is my version. Notice I used the switch statement, evaluating characters input using getch() to determine what to do. If the user chooses anything except an invalid response or ‘q’ to quit, the appropriate function is called. Also, notice that the user input conversions get the number to convert as a string then convert the number as an int using atoi(). This is not the only way to do a conversion from string to int, nor is it usually considered the best way, since it gives no error reporting, but it is a good, quick and dirty way to do conversions of this type.

This was written and compiled as a console program using Visual Studio Express 2012. It will not compile on Linux systems without a few changes. I have a similarly working version for Linux I will post immediately following. It is not perfect and there’s a quick workaround for a problem using scanf() but it gives a decent look at using switches and functions in Linux C.

#include <stdio.h>
char getDecision()
{
char decision;

system("cls");
puts("\n\nTemperature Converter\n\n");
puts("\t(c) Celsius to Fahrenheit\n\t(f) Fahrenheit to Celsius\n\t(t) Conversion Table\n\t(q) Quit\n\nMake your selection ...\n\n");
decision = getch();

return decision;
}

void displayTable()
{
/* print Fahrenheit-Celsius table
for fahr = 0, 20, ..., 300 */
int fahr, celsius;
int lower, upper, step;

lower = 0;
upper = 300;
step = 20;
fahr = lower;

puts("Conversion Table:\n\n");
while(fahr <= upper)
{
celsius = 5 * (fahr-32) / 9;
printf("%d\t%d\n", fahr, celsius);
fahr = fahr + step;
}
puts("\n");
}

void convertFtoC()
{
char numberString[256];
int celsius, fahr;
// get the number to convert as a string
puts("Converting Fahrenheit to Celsius\n\n");
puts("Enter number to convert ...\n\n");
fgets (numberString, 256, stdin);
// convert the string number to an integer
fahr = atoi(numberString);
// do the calculations
celsius = 5 * (fahr-32) / 9;
// print the results
printf("%d Fahrenheit = %d Celsius\n\n", fahr, celsius);
}

void convertCtoF()
{
char numberString[256];
int celsius, fahr;

// get the number to convert as a string
puts("Converting Celsius to Fahrenheit\n\n");
puts("Enter number to convert ...\n\n");
fgets (numberString, 256, stdin);
// convert the string number to an integer
celsius = atoi(numberString);
// do the calculations
fahr = (celsius * 9) / 5 + 32;
// print the results
printf("%d Celsius = %d Fahrenheit\n\n", celsius, fahr);
}

int main()
{
char decision = 'x';

decision = 'x';

while(decision != 'q')
{
decision = getDecision();

switch(decision)
{
case 'q':
system("cls");
puts("\n\nTemperature Converter\n\n");
puts("Program exited with no errors.\n\n");
exit(0);
break;
case 'c':
convertCtoF();
break;
case 'f':
convertFtoC();
break;
case 't':
displayTable();
break;
default :
puts("Invalid selection.\n\n");
}
puts("\nPress any key to continue ...\n\n");
getch();
}
return 0;

Now, here’s the code that compiles on a Linux machine.

#include <stdio.h> 
#include <stdlib.h> 
 
char getDecision() 
{ 
    char maindecision; 
 
    system("clear"); 
    puts("\n\nTemperature Converter\n\n"); 
    puts("\t(c) Celsius to Fahrenheit\n\t(f) Fahrenheit to Celsius\n\t(t) Conversion Table\n\t(q) Quit\n\nEnter your selection ...\n\n"); 
    maindecision = getchar(); 
 
    return maindecision; 
} 
 
void displayTable() 
{ 
    /* print Fahrenheit-Celsius table 
    for fahr = 0, 20, ..., 300 */ 
    int fahr, celsius; 
    int lower, upper, step; 
 
    lower = 0; 
    upper = 300; 
    step = 20; 
    fahr = lower;             
 
    puts("Conversion Table:\n\n"); 
    while(fahr <= upper) 
    { 
        celsius = 5 * (fahr-32) / 9; 
        printf("%d\t%d\n", fahr, celsius); 
        fahr = fahr + step; 
    } 
    puts("\n"); 
} 
 
void convertFtoC() 
{ 
    char numberString[256]; 
    int celsius, fahr; 
    // get the number to convert as a string 
    system("clear"); 
    puts("Converting Fahrenheit to Celsius\n\n"); 
    puts("Enter degrees Fahrenheit ...\n\n"); 
    // get and process the number 
    if(scanf("%s", numberString)) 
    { 
        // convert the string number to an integer 
        fahr = atoi(numberString); 
        // do the calculations 
        celsius = 5 * (fahr-32) / 9; 
        // print the results 
        printf("\n\n%d Fahrenheit = %d Celsius\n\n", fahr, celsius); 
    } 
    else printf("\n\nIncorrect input received.\n\n"); 
} 
 
void convertCtoF() 
{ 
    char numberString[256]; 
    int celsius, fahr; 
 
    // get the number to convert as a string 
    system("clear"); 
    puts("Converting Celsius to Fahrenheit\n\n"); 
    puts("Enter degrees Celsius ...\n\n"); 
    // get and process the number 
    if(scanf("%s", numberString)) 
    { 
        // convert the string number to an integer 
        celsius = atoi(numberString); 
        // do the calculations 
        fahr = (celsius * 9) / 5 + 32; 
        // print the results 
        printf("\n\n%d Celsius = %d Fahrenheit\n\n", celsius, fahr); 
    } 
    else puts("\n\nIncorrect input received.\n\n"); 
} 
 
int main() 
{ 
    char decision = 'x'; 
 
    decision = 'x'; 
 
    while(decision != 'q') 
    { 
        decision = getDecision(); 
 
        switch(decision) 
        { 
            case 'q': 
                system("clear"); 
                puts("\n\nTemperature Converter\n\n"); 
                puts("Program exited with no errors.\n\n"); 
                exit(0); 
                break; 
            case 'c': 
                convertCtoF(); 
                break; 
            case 'f': 
                convertFtoC(); 
                break; 
            case 't': 
                displayTable(); 
                break; 
            default : 
                puts("Invalid selection.\n\n"); 
        } 
        getchar(); 
        puts("\nEnter to continue ...\n\n"); 
        getchar(); 
    } 
    return 0; 
} 

C – Hello World!

InPursuitThe first program most people learn to write in any computer language is a program called “Hello World!” An online programmer friend recently mentioned that many of the basics you encounter in the programming language are built into “Hello World!” It got me thinking and I decided to post a short example of this classic program with explanations.

Yes, this program can be found many places and I’m reinventing the wheel by writing it. However, every person explains differently and, where someone else may have confused you, I may be the person to explain something in a way you will understand. Also, I find that communicating concepts helps me understand them better.

Here’s the program in C.

#include <stdio.h>

int main() {

   printf("\n\nHello World!\n\n");
   return 0;

}

The first line we encounter is:

#include <stdio.h>

This instruction is called a pre-processor directive. It loads the standard input/output library into the program. Part of the raw power of C is the low level control it gives you over the tasks your computer accomplishes and a good portion of this power is derived from the functionality that libraries provide. The most basic (and most often used) input and output are the keyboard and monitor, used to input and output data (interact with the program).

Libraries contain pre-programmed functions that expand what you can do with a computer language and “stdio.h” is one of the standard libraries included in the C language. You can also write functions of your own to complete repetitive tasks. In fact, there is one function that every C program must have.

Here’s the function that every C program must have to compile and run.

int main() {

}

Programmers refer to this function as “main.” The “int” refers to the type of data that the function returns when it exits, an integer. Functions are capable of returning different types of data or no data at all. A function that returns no data starts with “void” instead and there are other types. I have seen programs that start “main” with “void” instead of “int” but not all compilers will compile them. It is standard to start “main” with “int” and return an integer when the program exits, using a “return” statement.

The actual function is the word “main,” followed by parentheses and a pair of curly braces. The braces can contain data and commands. You can place data inside the parentheses that you want passed to the function. Our example contains a couple of lines of code inside the braces but the parentheses are empty. That is because we are not passing any outside data to “main.”

Here is an example.

return 0;

The “return” statement is used to return data when the function completes. It’s standard for the “main” function to return a zero when it completes, indicating that the program completed and exited normally. The “;” at the end of the line is like the period at the end of a sentence in English. It notifies the compiler that this is the end of the statement.

The one line of the program we haven’t discussed is:

printf("\n\nHello World!\n\n");

This line calls the “printf” function and tells it to print the “Hello World!” message to stdout, which is usually the computer screen. The printf() is the complete function (you only add the braces to functions in which you are writing the commands), everything between the parentheses is the data you are passing to the function and the semicolon at the end of the line tells the compiler this is the end of the statement.

Everything between the double quotes is a string of characters sent to the “printf” function. You can pass data in other ways but, when you are typing a string of characters to send, you must enclose them in double quotes. The “\n” is a newline character and printf() will respond by moving down a line on your screen before writing the message. In this case, the message is printed two lines down from the command used to call the program and is followed by two more new lines, ensuring that there is space before and after the program’s output. This makes the output more readable because it is not surrounded by clutter.

I hope you enjoyed the article. I’m looking forward to any comments, questions or corrections you may have.

The Perfect Cup of Coffee

image

Musicians, filmmakers and programmers are very serious about their respective arts. Having experience working as all three, I have the somewhat unfortunate experience of being a workaholic. However, I also have the very fortunate experience of a shared passion that all three embrace without hesitation, an experience that creates an almost religious fervor in the more artistic members of these groups. As you have probably surmised by the title of the article, I am talking about the wonderful elixir whose parent bean causes goats to dance on the mountain tops, that dark and energizing brew we know as coffee.

As magic elixirs go, this is arguably the very finest. There are many different roasts available in just about every store in my country and, quite probably, throughout the world. People search endlessly for the method of making the perfect cup. It is, of course, a somewhat subjective matter, so you may argue with this article with no fear of chastisement from me. However, I am happy to present to you my recipe for the perfect cup of coffee.

It’s all about the bean!

Perfect coffee starts with a perfect coffee bean and a perfect roasting of that bean. Most people are used to drinking a bitter concoction consisting of beans that are almost burned in comparison with what I prefer. High attitude beans are considered the best quality bean and shade grown beans are all the rage.

High altitude beans have the unfortunate trait of having a high acid content. For people who drink coffee on a regular basis, this can result in stomach problems. Darker roasts present the drinker with a bitter flavor profile and, you guessed it, a higher acid content. If you imbibe to the extreme, grab the Prilosec and hang on for the ride.

Personally, I prefer a mild, Columbian roast. In fact, I smell beans before making a purchase to make sure they have the rich flavor I prefer. My favorite to date is a mild, Columbian roast from Whole Foods’ Allegro coffees. The coffee is shade grown, which matures the bean more slowly for a richer flavor. There is another mild coffee at Whole Foods called Ubuntu that I intend to try. The name embraces the African philosophy that a man is only a man through his interaction with others, signifying that the things we do to and for others defines who we are. It should also be a favorite to Linux programmers who find it because it is also the name of an operating system that is totally free and open source and embraces this philosophy.

Grind and brew!

I only buy whole beans, grinding at the time of brewing. I eschew the burr grinders that evenly grind every bean to consistent perfection, preferring to use a simple blade grinder. My family owns one of those fancy, automatic machines that grinds the beans and brews the coffee at pre-programmed times but we rarely use it. Instead, we have a larger French press and a couple of single-serving modeIs designed to brew a single cup. Mine is pictured.

Grinding beans for a single serving presents a problem. Grinders are designed to brew a regular pot of coffee, The smaller amount of beans, usually a heaping tablespoon for my perfect cup of coffee, does not grind properly with a sustained grind. Instead, l use six to eight short pulses, stopping when the grinds are at the desired consistency. I do not grind them as fine as I would for a regular pot of coffee made in an automatic drip coffee maker because the screen on the French press allows the finer grounds to slip into the coffee.

For my perfect cup of coffee, I prefer to heat the water in the cup. I don’t mind microwaved water. Some people say it tastes different to them than boiled water but I can’t tell the difference. Heating the water in my coffee cup also makes the cup hot. Added ingredients do not contribute as much to the cooling of the drink when they sit in a hot cup. I am assured a piping hot cup every time.

I brew the coffee in the French press for five minutes, then press it and pour it into the cup.

Do added ingredients spoil the brew?

Some people prefer a hot, black, bitter cup of Joe. Personally, I prefer a blending of flavors in my coffee. I found a long time ago that a little ground cinnamon in the brew had others raving about the wonderfully delicious coffee I made. I have since learned that the Mexican people use a bit of cinnamon and brown sugar in their coffee. I don’t use the powder, which contaminates the drink. Instead, I grind a chunk of cinnamon stick to a coarser consistency and add it to the coffee grounds. I grind it separately in my coffee grinder, using short bursts, because it grinds differently than the coffee beans.

Like the people of Mexico, I love brown sugar in my coffee. White sugar will also do nicely in a pinch but it lacks the darker, more robust, molasses flavor of its less processed cousin. Four to four and a half teaspoons is my preffered amount,

l love cream in coffee but it is loaded with saturated fats. Except for special occasions, I use 2% milk. I prefer organic milk. There is a difference in flavor. I use a double shot glass to measure a perfect two ounces in my cup.

As I stated before, I let these added ingredients sit in the hot cup while brewing. This helps ensure that my coffee is hot when I serve it. One other addition I use on rare occasions is a shot or two of rum or brandy. Presidente is my favorite brandy for this purpose, another wonderful flavor from Mexico. More often, I choose Flor de Cana, a Nicaraguan rum with a wonderful, dark, molasses flavor.

Even the cup matters!

Yes, even the cup matters. I have a great coffee cup I was given at a leadership conference presented by Breakfast With Fred a few years ago, It is a great organization whose goal is not coffee cups, but furthering ethical leadership in business. However, they also created the perfect coffee cup for my purposes. It is slightly larger than a standard cup, allowing addition of my extras while still giving me room for a full cup of my favorite beverage.

Enjoying it responsibly!

Too much of anything is bad for you. I enjoy responsible amounts of coffee. While it gives a nice boost to your day, and it tastes great, coffee’s properties and slightly addictive quality, make it a drink best enjoyed in limited amounts. I invite you, oh coffee lover, to try my recipe for a perfect cup of coffee. Conform it to your taste and enjoy it in responsible amounts so it can be a boon to your day.

Windows and Virus Programming

InPursuitThe fine programmers at Microsoft have a problem. To put it simply, their platform is the most heavily targeted by malicious code. However, that is beginning to change.

I have read that Apple has been targeted with viruses recently, though it’s not as frequent, yet. Linux has traditionally been exempt from malicious code attacks but Linux systems are growing in popularity and have become targets. The Android operating system has its viruses and, now, even scripting languages like PHP are starting to see virus activity. I recently read the code of a PHP virus that attaches itself to the program and does some nasty things.

Microsoft programmers, however, have not been idle. I’ve been learning programming on Linux but recently bought a laptop with Windows 8. It’s large enough to let me host multiple Linux operating systems on VirtualBox, so I’ve been playing and having fun.

I’ve also installed Microsoft Visual Studio Express 2012 and been playing with some old school tools of virus programmers with interesting results.

Programs that Delete Themselves

One interesting things virus programmers have been able to do is make their viruses disappear after they’ve done their work. The following code uses the remove() command to delete argv[0], the reference to the program that is running. Effectively, the program deletes itself. I found the original code on several websites and couldn’t compile it under Windows or Linux with a modern OS. I rewrote it as you see here.

This code will run under Linux and the program will delete itself. In Windows, however, it returns a very visible error. Not very good for a virus that wants to remain incognito.

// This program will no longer destroy itself under Windows.
 // Windows returns an error message.
#include<stdio.h>
 #include<conio.h>
 #include<dos.h>
 int main(int argc, char argv[])
 {
 printf("This program will destroy itself when you press a key!\n");
 getch();
 remove(argv[0]);/*array of pointers to command line arguments*/
 return 0;
 }

I became intrigued by this and decided to try another bit of source code from the Internet. This one allows one file to be embedded into another file. After some reworking of the old code, I got it running under Windows. It will embed a program into another program. The program that receives the information can still run and the file can be extracted into an executable program.

Three things to note about this program are that it actually takes the target file and places it into the source (which can be confusing), Windows will not let it put itself into another file and Windows will not run the extracted file.

#include<stdio.h>
 #include<conio.h>
 #include<fcntl.h>
 #include<sys/types.h>
 #include<sys/stat.h>
 #include<stdlib.h>
 #include<string.h>
 #include <io.h>
void embed(void);
 void extract(void);
char buff[1],sname[128],tname[128],dname[128],choice;
 unsigned long int size=0;long int psize=0;int outh,bytes=0;
 FILE *source,*target,*data;
void main()
 {
 while(1)
 {
 system("cls");
 puts("\n\t\t\t\tFILE EMBEDDING UTILITY BY SRIKANTH\n\n\n");
 puts("1.Embed A File 2. Extract A File 3.Exitn");
 choice=getch();
 switch(choice)
 {
 case '1':
 embed();
 getch();
 break;
 case '2':
 extract();
 getch();
 break;
 default:
 exit(0);
 }
 }
 }
void embed()
 {
 puts("\nEnter The Source Filename\n");
 scanf("%s",sname);
 source=fopen(sname,"rb+");
 if(source==NULL)
 {
 puts("\nCannot Open The Source File\n");
 return;
 }
 puts("\nEnter The Target Filename\n");
 scanf("%s",tname);
 outh=open(tname,_O_WRONLY | _O_BINARY);
 if(outh==-1)
 {
 puts("\nCannot Open The Target File\n");
 return;
 }
 printf("\nReading The Source File Please Wait…\n");
 while((bytes=read(outh,buff,1))>0)
 size+=bytes;
 data=fopen("Data.cfg","w");
 if(data==NULL)
 {
 puts("\nCannot Create Configuration The File\n");
 return;
 }
 fprintf(data,"%lu",size);
 close(outh);
 fclose(data);
 target=fopen(tname,"rb");
 if(target==NULL)
 {
 puts("Cannot Open Target File\n");
 return;
 }
 printf("\nEmbedding Please Wait…\n");
 fseek(source,0,SEEK_END);
 while(fread(buff,1,1,target)>0)
 fwrite(buff,1,1,source);
 fcloseall();
 printf("\nEmbedding Completed Successfully\n");
 }
void extract()
 {
 printf("\nEnter The Source Filename\n");
 scanf("%s",sname);
 source=fopen(sname,"rb");
 if(source==NULL)
 {
 printf("\nCannot Open The Source File\n");
 return;
 }
 printf("\nEnter The Target Filename(eg: abc.exe)\n");
 scanf("%s",tname);
 printf("\nEnter The Configuration Filename(eg: DATA.cfg)\n");
 scanf("%s",dname);
 data=fopen(dname,"r");
 if(data==NULL)
 {
 printf("\nConfiguration File Not Found\n");
 return;
 }
 fscanf(data,"%ld",&psize);
 target=fopen(tname,"wb");
 if(target==NULL)
 {
 puts("\nCannot Open The Target File\n");
 return;
 }
 printf("\nExtracting Please Wait…\n");
 fseek(source,-psize,SEEK_END);
 while((fread(buff,1,1,source))>0)
 fwrite(buff,1,1,target);
 printf("\nFile Extraction Completed Successfully\n");
 fcloseall();
 }

Admittedly, a programmer who is good at building virus programs may be able to find workarounds for this and, also admittedly, I may have overlooked something on the second program in trying to get the code to work, but it’s clear that Microsoft added to its operating system in ways that make it harder to use some of the old tricks. This may be why many of the new virus programs are a bit more straightforward and rely on fooling the user into executing them. Viruses are still a big threat under Windows but the face of virus programming is changing in Windows because of the work Microsoft’s programmers do to make it safer to use.

It’s a bit scary that I can run potentially malicious code on Linux systems that won’t work as expected under Windows.

Invoking Javascript on a webBrowser.Document in C#

Houston, we have a problem! Invoking Javascript on a page through a webbrowser in a C# application.Houston, we have a new problem!

So, I’m working away at this little project, bemoaning the fact that I can’t get posts to populate in the textarea on this particular social site. My login and logout code works well but there’s a problem with the status updates.

This is one of those text boxes that grows when you click it with the mouse or Tab into it. The problem seems to be a Javascript that needs to be invoked properly for the text box to appear. I want to automate posting, I don’t want to use 0Auth and the API and I want this all to run automatically with no need for human interaction.

Here’s the <script> in the <head> of the page.

<script>window.Bootloader && Bootloader.done(["6HM2D"]);</script>

Here’s the way it appears in <textarea> on the page.

onkeydown="window.Bootloader &amp;&amp; Bootloader.loadComponents([&quot;control-textarea&quot;], function() { TextAreaControl.getInstance(this) }.bind(this)); "

I’m not the Javascript guy but it appears that the script is being called with different options to open the text box in response to a key press or a mouse click. I’ve tried simulating a human entering the data. First, I tried just copying the data into the <textarea> element, followed by having the software click the button. This didn’t work. I followed by trying to simulate a MouseDown event but I’m new to C# and I’m not sure I did it properly. I finally used Focus() to get focus on the <textarea> and found that, if I follow it with putting text into the initial box, the box will grow, the text will disappear and I won’t be able to add anything to it.

What are my possible solutions?

As I see it, I have three possible solutions.

  1. Find a way to convince the program that the text area was clicked so it will expand before entering text.
  2. Find a way to bypass it, entering values and attributes to that <textarea> that will negate the need to do all the clicking and entering.
  3. Use HttpWebRequest to bypass the need for interacting with the webBrowser.

I’ve tried 1 but I may have not been executing it properly. I dove blindly into C# with no training because it is so easy for me to read after learning the syntax for C, C++, Java and PHP. I have not been able to find 2, a way to bypass it but I’m not sure what all their code does. That bring us to 3 and I have not studied HttpWebRequest yet, though I can tell you that will be on my list now.

If you, dear friend, can offer some help with this problem, it would be greatly appreciated.