Monday 28 November 2011

Can printf() be used in a Windows program? in C programming

Can printf() be used in a Windows program?

The standard C function printf() can be used in a Microsoft Windows program; however, it has no usefulness to the Windows environment, and it does not produce the same result as in a DOS environment. The printf() function directs program output to stdout, the standard output device. Under DOS, the standard output device is the user’s screen, and the output of a printf() statement under a DOS program s immediately displayed.

Conversely, Microsoft Windows is an operating environment that runs on top of DOS, and it has its own mechanism for displaying program output to the screen. This mechanism comes in the form of what is called a device context. A device context is simply a handle to a portion of the screen that is handled by your program. The only way to display output on-screen in the Microsoft Windows environment is for your program to obtain a handle to a device context. This task can be accomplished with several of the Windows SDK (Software Development Kit) functions. For instance, if you were to display the string “Hello from Windows!” in a windows program, you would need the following portion of code:

void print_output(void)
{
...
hdcDeviceContext = BeginPaint(hwndWindow, psPaintStruct);
DrawText(hdcDeviceContext, “Hello from Windows!”, -1,
&rectClientRect, DT_SINGLELINE);
...
}

Put simply, all output from a Windows program must be funnelled through functions provided by the Windows API. If you were to put the line

printf(“Hello from Windows!”);

into the preceding example, the output would simply be ignored by Windows, and your program would appear to print nothing. The output is ignored because printf() outputs to stdout, which is not defined under Windows. Therefore, any C function such as printf() (or any other function that outputs to stdout) under the Windows environment is rendered useless and should ultimately be avoided. Note, however, that the standard C function sprintf(), which prints formatted output to a string, is permissible under the Windows environment. This is because all output from the sprintf() function goes directly to the string and not to stdout.

Cross Reference:

XXI.9: What is the difference between Windows functions and standard DOS functions?

No comments:

Post a Comment