"C" Programming Language - Stdio

Started by sivaji, Jan 10, 2008, 06:57 PM

Previous topic - Next topic

sivaji

Programming Stuffs in "C" - Technical Skills for INTERVIEW

Stdio

1: What's wrong with this code:
   char c;
   while((c = getchar()) != EOF)...

You forgot to include space for the terminating NUL character, so the compiler can't find the end of c without overwriting other memory. In all probability, after the user types ``n<return>'', your code will look like
char cn
while((c = getchar()) != EOF)...

which won't compile.

Also, the ellipsis is not legal outside of function protoypes.

Try
char c[2]; /* include space for terminating NUL */
while ((c = getchar()) != EOF)
   ;


2: How can I print a ``%'' character in a printf format string? I tried ``\%'' but it didn't work.

Break the '%' sign out. i.e., fprintf("foo " "%" "%d\n", foo);

Alternatively, try

sprintf("o" "/" "o") to get a "%".

The astute reader will notice that the latter example uses sprintf, and the former fprintf - this is because sprintf() works by characters, or strings, while fprintf (``fast printf'') works on files.

3: Why doesn't the code scanf("%d", i); work?

You need to do this a bit differently; you should always check for the return from scanf, so try something like
i = 1;
if ((scanf, "%d", i) == 1)

to make sure you're reading correctly. (The assignment to i is so that, if scanf fails, you still have a legal value in i.)

4: Once I've used freopen, how can I get the original stdout (or stdin) back?

Call main() - the environment will be restored.

5: Why won't the code
   while(!feof(infp)) {
      fgets(buf, MAXLINE, infp);
      fputs(buf, outfp);
   }
work?

Because the end of file character is not detected on files named ``infp''. (Introverted-iNtuitive-Feeling-Perceptive, that is.) Also, it may be that the file was opened in text mode, where an end of file is read as a capital 'Z' on most machines, and feof() only looks for 'control Z'.

6: How can I redirect stdin or stdout to a file from within a program?

execlv("main()" "> file", argv);
Am now @ Chennai