Archive for the 'C' Category

C, Source Code

Growing String in c

This article contains the source code for a c utility that manages a growing string, and a brief explanation of the code.

To obtain this, we make something similar to a c++ class: a struct with associated functions. The functions add characters to the string in the struct, and allocate more memory space when the string is full.

This is usefull when we are working with string with an unknow length (e.g. we are reading a file).

The struct containing the string is the following:

// Struct containing the growing string
typedef struct
{
	// string
	char * text;
	// string length (with zero terminator)
	int length;
	// string capacity
	int capacity;
} growing_string;

The text variable is where the string is allocated, length is the current string lenght and capacity is the memory allocated for the string.

To better understand the difference between length and capacity, look at the next image:

Capacity-Length

Capacity is the total space allocated for the string, while length is the actual number of character of the string, including the \0 terminator (the special character that close the string). If we add enough characters and the length is greater than the capacity, we need to allocate more memory for the string.

Continue Reading »

C, Source Code

How to use poEdit

In this guide I will explain how to simplify the localization process of a software written in c++ using “wxWidget (a cross platform toolkit), with poEdit.
poEdit offers to developers a conventient approach to localizazion, and there is no need to modify the source code by hand to modify translations, because they are all stored on a catalog file that is easy editable.

Logo poEdit

To prepare the source code to the localization, we must sorround all strings that we want to localize with the macro “_()”, for example:

...
wxMessageBox( _("localized string") );
...
wxMessageBox( wxT("not localized string") );

Continue Reading »

C, Source Code, USBAutoStart

First public version of USBAutoStart!

USB AutoStart

Usbautostart is a Windows utility that performs autoplay for usb mass storage device. Windows avoid the autoplay on the removable medias for security reasons, but with this program you can bypass this limit and you can choose to launch a program in the usb pen when you plug it.
The program will also close all applications running from the device when you try to “safety remove” it.

Screenshots:

Usb peripheral detection (the red icon on the left is Mozup, the program started from the usb pen):
USB AutoStart Inserting device

Usb removal:
USB AutoStart Removing device

The project is hosted on sourceforge, and it’s released under GPL license, so it’s completely free and open source! :)

Download Usb Autostart

C, Quiz

Coders4fun Quiz #1

What will be printed using this c++ code?

#include <iostream>

int main()
{
	int i = 0;
	for (i = i == 0; i < 9; i = 1 + i * 2);
		std::cout<<i<<std::endl;
	return 0;
}

Please don’t cheat using a compiler! :)

P.S.
Of course the example compiles!

C, Source Code, UDP Communication

UDPListener: Receiving UDP messages in C#

This post is part of the UDPCommunication project.

UDP - User Datagram Protocol

The class in this post allows, in an easy and fast manner, to receive UDP messages. You don’t need to be a socket expert to use the class, cause you only need to write few rows of code to use it. Following, a little example showing how to use the class:

private void InitConnection()
{
	m_udpListener = new UDPListener(m_port, new byte[4] { 0, 0, 0, 0 });
	m_udpListener.MessageReceived += new UDPMessageReceivedDelegate(udpListener_MessageReceived);
}

Continue Reading »

C, Source Code, Windows

Reboot or Shutdown a pc

This is a little how-to that explains how to shutdown or reboot a Windows machine in c++ .
In the source code you will find the function ShutDown, definied as follow:

bool ShutDown(bool restart)

The function shutdowns or reboots the pc, and returns false if the shutdown can’t be done (for example a process denied the power off).

Shut Down

So, to shutdown the pc, you only have to call the function and check if the shutdown was done.

if (!ShutDown(false))
{
	// shutdown not done.
}

Part of source code following:
Continue Reading »

C, Source Code, UDP Communication

UDPSender: Sending UDP messages in C#

This post is part of the UDPCommunication project.

Header UDP

This is a class that allows to send UDP messages in C# with an unbelievable semplicity.
To create the class you only need to create it, specifying a port for the udp communication, eg 3125 in this case:

try
{
	INetworkSender udpSender = new UDPSender(3125)
}
catch(UDPSenderException e)
{
        	// error during the socket initialization
}

Sending a message to an host is simple: call the SendMessage method specifying the receiver (with an host name, like “www.coders4fun.com“, or with an ip, like “192.168.10.6“) and a byte array containing the message.
Continue Reading »

C, Source Code

Edit form elements from a Thread

Scenario:
The program has to execute a long operation (such as a downloaded file from the internet) when the user clicks on a button, but during the operation the user has the opportunity to interact with the program, and the program gives a visual feedback of the task completion percentage.
Easy, but not working, solution:
To solve a problem like that we need to use a Thread that executes the task in a separate context from the main Form, otherwise, if we execute the long operation in the onClick method of the button, the form will remain frozen during the task execution. The problem comes out when the program tries to update the form from the thread:

private void button1_Click(object sender, EventArgs e)
{
    testThread = new Thread(threadProc);
    testThread.Start();
}

public void threadProc()
{
    // wast a lot of time...
    for (int i = 1; i <= 10; i++)
    {
        Thread.Sleep(250);
        progressBar.Value = i * 10;
    }
    MessageBox.Show("Operation Completed!");
}

Unfortunately, the code that assigns the value to the progressBar will produce an exception like that:
“Illegal cross-thread operation: Control ‘progressBar1′ accessed from a thread other than the thread it was created on.”

lock

Continue Reading »

C

C# Threads using anonymous methods

When we want to use a Thread in C#, we usually write a method with the code that the Thread must execute, and when we create the Thread object we set its delegate to the method already created:

public void DoSomethingUsefull()
{
	for (int i = 0; i < 100; i++)
	{
		// doing something...
		Thread.Sleep(500);
	}
}

static void Main()
{
	// here we create the thread, passing to it the right delegate
	Thread t = new Thread(DoSomethingUsefull);
	t.Name = "Test Thread";
	t.Start();
}

dual core

To create a Thread, C# offers the opportunity to use anonymous methods. To use an anonymous method, we need to write the Thread’s code inside the code that creates the Thread using the delegate keyword:
Continue Reading »

C, MySQL

Convert a DateTime Object in a SQL field

This post is part of the SQLStringBuilder project. For the latest version of the code i suggest to take the source code from the CVS.

If we want to insert a date in a SQL string in C#, the solution seems obvious:

DateTime date = DateTime.Now;
string sql = "INSERT INTO tableWithDate VALUES(1, "+ date.ToString() + ")";

Unfortunately this code can’t work! The function DateTime.ToString() returns a string like 23/02/2007 19.00.49, while MySQL wants a string like 2007-02-23 19:00:49. The following static function converts a DateTime object in a valid date field for MySQL:

public static string GetSQLDate(DateTime date)
{
	string sql;
	sql = date.Year.ToString() + "-" + date.Month.ToString() + "-" + date.Day.ToString() + " "
	+ date.Hour.ToString() + ":" + date.Minute.ToString() + ":" + date.Second.ToString();
	return sql;
} 

I inserted the method in a utility class, that i called Utils, so the working code is:

string sql = "INSERT INTO tableWithDate VALUES(1, "+ Utils.GetSQLDate(date) + ")";

Next »