solution C Puzzle #5

Output:
12
f(1,2)
Reason:
the # operator stringizes its operand, i.e. it puts double quotes
around it.
The ## operator 'glues' its operands together.

The preprocessor expands macro definitions in the text.
It keeps expanding macros as long as it finds any; to block
recursion 
it won't expand a macro that is being expanded already.
in the first printf(), firstly, it is replacing h(f(1,2)) by
g(f(1,2)), and then immediately in the same pass, it calculated
its argument i.e. f(1,2), resulting in "12". Thus getting g("12")
in place of h(f(1,2)). This g("12") results in a string "12".

In short, in first printf()
h(f(1,2)) >> g("12") >> "12"

In the second printf(),
g(f(1,2)) >> "f(1,2)"

solution C Puzzle #4

The result i get after execution:
hello-errhello-errhello-errhello-errhello-errhello-errhello-errhello-errhello-errhello-errhello-err.......

modify the code to the following:
while(1)
{
fprintf(stdout,"hello-out\n");
fprintf(stderr,"hello-err\n");
sleep(1);
}


everything works.

---------------------------
Reason: stderr is usually unbuffered, so every small piece of text sent to it gets printed immediately. stdout is usually buffered, so that output to it is collected in a large block which is only output when filled, or when a '\n' appears, because this is much faster.

If there is material in the buffer and the program exits, I think it is not flushed automatically.

You can use fflush to force the output, and you can change the buffering, using setbuf.

The above is a simplification, but all you need to know is in the manual page for 'setbuf'.
-----------------

Facts about fprintf:
courtsey:www.learn-programming.za.net Rank:6794

Files let you store data on secondary storage such as a hard disk so that your programs can later retrieve that data again. There are 2 types of files which are text files and data files.

Text files

Text files are used for storing character strings in a file. To create a text file you must first declare a file pointer.
#include<stdio.h>

int main()
{
   FILE *f;
   return 0;
}

You must then open the file using the fopen function. fopen takes 2 parameters which are the file name and the open mode. fopen returns a file pointer which we will assign to the file pointer called f.
#include<stdio.h>

int main()
{
   FILE *f;
   f = fopen("test.txt","w");
   return 0;
}

The above example will create a file called test.txt. The "w" means that the file is being opened for writing and if the file does not exist then it will be created. Here are some other open modes:
rOpen for reading
r+Open for reading and writing
wOpen for writing and create the file if it does not exist. If the file exists then make it blank.
w+Open for reading and writing and create the file if it does not exist. If the file exists then make it blank.
aOpen for appending(writing at the end of file) and create the file if it does not exist.
a+Open for reading and appending and create the file if it does not exist.
To write a string to the file you must use the fprintf command. fprintf is just like printf except that you must use the file pointer as the first parameter.
#include<stdio.h>

int main()
{
   FILE *f;
   f = fopen("test.txt","w");
   fprintf(f,"Hello");
   return 0;
}

When you are finished using a file you must always close it. If you do not close a file then some of the data might not be written to it. Use the fclose commmand to close a file.
#include<stdio.h>

int main()
{
   FILE *f;
   f = fopen("test.txt","w");
   fprintf(f,"Hello");
   fclose(f);
   return 0;
}

The fgets command is used when reading from a text file. You must first declare a character array as a buffer to store the string that is read from the file. The 3 parameters for fgets are the buffer variable, the size of the buffer and the file pointer.
#include<stdio.h>

int main()
{
   FILE *f;
   char buf[100];
   f = fopen("test.txt","r");
   fgets(buf,sizeof(buf),f);
   fclose(f);
   printf("%s\n",buf);
   return 0;
}

Data files

A data file is used to store types of data such as integers. When you open a data file you must add the letter b to the open mode parameter of fopen.
#include<stdio.h>

int main()
{
   FILE *f;
   f = fopen("test.dat","wb");
   fclose(f);
   return 0;
}

fwrite is used to write to a file. The first parameter of fwrite is a pointer to the variable that you want to write to the file. The second parameter is the size of the variable that must e written. The third parameter is the number of variables to be written. The fourth parameter is the file pointer of the file you want to write to.
#include<stdio.h>

int main()
{
   FILE *f;
   int buf;
   f = fopen("test.dat","wb");
   buf = 100;
   fwrite(&buf,sizeof(buf),1,f);
   fclose(f);
   return 0;
}

fread is used to read from a file and is the same as fwrite except that the data is read into the variable instead of writing from it. You must remember to change the file mode to read.
#include<stdio.h>

int main()
{
   FILE *f;
   int buf;
   f = fopen("test.dat","rb");
   fread(&buf,sizeof(buf),1,f);
   printf("%d\n",buf);
   fclose(f);
   return 0;
}

Data files using structures

You can read and write structures to data files in the same way as you do with any other data type. Here is an example:
#include<stdio.h>

struct
{
   char name[100];
   int age;
} p;

int main()
{
   FILE *f;
   strcpy(p.name,"John");
   p.age = 25;
   f = fopen("test.dat","wb");
   fwrite(&p,1,sizeof(p),f);
   fclose(f);
   return 0;
}



Facts about Sleep():
courtsey: http://www.delorie.com/gnu/docs/glibc/libc_445.html

Sleeping

The function sleep gives a simple way to make the program wait for a short interval. If your program doesn't use signals (except to terminate), then you can expect sleep to wait reliably throughout the specified interval. Otherwise, sleep can return sooner if a signal arrives; if you want to wait for a given interval regardless of signals, use select (see section 13.8 Waiting for Input or Output) and don't specify any descriptors to wait for.

Function: unsigned int sleep (unsigned int seconds)
The sleep function waits for seconds or until a signal is delivered, whichever happens first. If sleep function returns because the requested interval is over, it returns a value of zero. If it returns because of delivery of a signal, its return value is the remaining time in the sleep interval. The sleep function is declared in `unistd.h'.
Resist the temptation to implement a sleep for a fixed amount of time by using the return value of sleep, when nonzero, to call sleep again. This will work with a certain amount of accuracy as long as signals arrive infrequently. But each signal can cause the eventual wakeup time to be off by an additional second or so. Suppose a few signals happen to arrive in rapid succession by bad luck--there is no limit on how much this could shorten or lengthen the wait.
Instead, compute the calendar time at which the program should stop waiting, and keep trying to wait until that calendar time. This won't be off by more than a second. With just a little more work, you can use select and make the waiting period quite accurate. (Of course, heavy system load can cause additional unavoidable delays--unless the machine is dedicated to one application, there is no way you can avoid this.)
On some systems, sleep can do strange things if your program uses SIGALRM explicitly. Even if SIGALRM signals are being ignored or blocked when sleep is called, sleep might return prematurely on delivery of a SIGALRM signal. If you have established a handler for SIGALRM signals and a SIGALRM signal is delivered while the process is sleeping, the action taken might be just to cause sleep to return instead of invoking your handler. And, if sleep is interrupted by delivery of a signal whose handler requests an alarm or alters the handling of SIGALRM, this handler and sleep will interfere.
On the GNU system, it is safe to use sleep and SIGALRM in the same program, because sleep does not work by means of SIGALRM.

Function: int nanosleep (const struct timespec *requested_time, struct timespec *remaining)
If resolution to seconds is not enough the nanosleep function can be used. As the name suggests the sleep interval can be specified in nanoseconds. The actual elapsed time of the sleep interval might be longer since the system rounds the elapsed time you request up to the next integer multiple of the actual resolution the system can deliver. *requested_time is the elapsed time of the interval you want to sleep. The function returns as *remaining the elapsed time left in the interval for which you requested to sleep. If the interval completed without getting interrupted by a signal, this is zero. struct timespec is described in See section 21.2 Elapsed Time. If the function returns because the interval is over the return value is zero. If the function returns -1 the global variable errno is set to the following values:
EINTR
The call was interrupted because a signal was delivered to the thread. If the remaining parameter is not the null pointer the structure pointed to by remaining is updated to contain the remaining elapsed time.
EINVAL
The nanosecond value in the requested_time parameter contains an illegal value. Either the value is negative or greater than or equal to 1000 million.
This function is a cancellation point in multi-threaded programs. This is a problem if the thread allocates some resources (like memory, file descriptors, semaphores or whatever) at the time nanosleep is called. If the thread gets canceled these resources stay allocated until the program ends. To avoid this calls to nanosleep should be protected using cancellation handlers.
The nanosleep function is declared in `time.h'.

 Facts about stdout:
courtsey: computer.howstuffworks.com Rank: 837


Text files in C are straightforward and easy to understand. All text file functions and types in C come from the stdio library.
When you need text I/O in a C program, and you need only one source for input information and one sink for output information, you can rely on stdin (standard in) and stdout (standard out). You can then use input and output redirection at the command line to move different information streams through the program. There are six different I/O commands in <stdio.h> that you can use with stdin and stdout:
  • printf - prints formatted output to stdout
  • scanf - reads formatted input from stdin
  • puts - prints a string to stdout
  • gets - reads a string from stdin
  • putc - prints a character to stdout
  • getc, getchar - reads a character from stdin
The advantage of stdin and stdout is that they are easy to use. Likewise, the ability to redirect I/O is very powerful. For example, maybe you want to create a program that reads from stdin and counts the number of characters:
#include <stdio.h>
#include <string.h>

void main()
{
    char s[1000];
    int count=0;
     while (gets(s))
        count += strlen(s);
    printf("%d\n",count);
}

Enter this code and run it. It waits for input from stdin, so type a few lines. When you are done, press CTRL-D to signal end-of-file (eof). The gets function reads a line until it detects eof, then returns a 0 so that the while loop ends. When you press CTRL-D, you see a count of the number of characters in stdout (the screen). (Use man gets or your compiler's documentation to learn more about the gets function.)
Now, suppose you want to count the characters in a file. If you compiled the program to an executable named xxx, you can type the following:
xxx < filename

Instead of accepting input from the keyboard, the contents of the file named filename will be used instead. You can achieve the same result using pipes:
cat < filename | xxx

You can also redirect the output to a file:
xxx < filename > out

This command places the character count produced by the program in a text file named out.
Sometimes, you need to use a text file directly. For example, you might need to open a specific file and read from or write to it. You might want to manage several streams of input or output or create a program like a text editor that can save and recall data or configuration files on command. In that case, use the text file functions in stdio:
  • fopen - opens a text file
  • fclose - closes a text file
  • feof - detects end-of-file marker in a file
  • fprintf - prints formatted output to a file
  • fscanf - reads formatted input from a file
  • fputs - prints a string to a file
  • fgets - reads a string from a file
  • fputc - prints a character to a file
  • fgetc - reads a character from a file

solution C Puzzle #3

Answer: This will print "1" only once.

Clear your concepts regarding continue statement.

Courtsey: msdn.microsoft.com
The continue statement passes control to the next iteration of the nearest enclosing do, for, or while statement in which it appears, bypassing any remaining statements in the do, for, or while statement body.

jump-statement:
continue;
The next iteration of a do, for, or while statement is determined as follows:
  • Within a do or a while statement, the next iteration starts by reevaluating the expression of the do or while statement.
  • A continue statement in a for statement causes the first expression of the for statement to be evaluated. Then the compiler reevaluates the conditional expression and, depending on the result, either terminates or iterates the statement body. See The for Statement for more information on the for statement and its nonterminals.
This is an example of the continue statement:
while ( i-- > 0 ) 
{
    x = f( i );
    if ( x == 1 )
        continue;
    y += x * x;
}
In this example, the statement body is executed while i is greater than 0. First f(i) is assigned to x; then, if x is equal to 1, the continue statement is executed. The rest of the statements in the body are ignored, and execution resumes at the top of the loop with the evaluation of the loop's test.