C MCQs: Error Handling- Part 1

Here is a listing of C multiple choice questions on “Error Handling” along with answers, explanations and/or solutions:

1. What is the output of this C code if there is no error in stream fp?

#include <stdio.h>
    int main()
    {
        FILE *fp;
        fp = fopen("newfile", "w");
        printf("%d\n", ferror(fp));
        return 0;
    }

a) Compilation error
b) 0
c) 1
d) Any nonzero value

2. Within main, return expr statement is equivalent to.

a) abort(expr)
b) exit(expr)
c) ferror(expr)
d) None of the mentioned

3. What is the output of this C code?

#include <stdio.h>
    int main()
    {
        FILE *fp;
        char c;
        int n = 0;
        fp = fopen("newfile1.txt", "r");
        while (!feof(fp))
        {
            c = getc(fp);
            putc(c, stdout);
        }
    }

a) Compilation error
b) Prints to the screen content of newfile1.txt completely
c) Prints to the screen some contents of newfile1.txt
d) None of the mentioned

4. What is the output of this C code?

#include <stdio.h>
    int main()
    {
        FILE *fp = stdout;
        stderr = fp;
        fprintf(stderr, "%s", "hello");
    }

a) Compilation error
b) hello
c) Undefined behaviour
d) Depends on the standard

5. What is the output of this C code?

#include <stdio.h>
    int main()
    {
        char buf[12];
        stderr = stdin;
        fscanf(stderr, "%s", buf);
        printf("%s\n", buf);
    }

a) Compilation error
b) Undefined behaviour
c) Whatever user types
d) None of the mentioned

6. stderr is similar to?
a) stdin
b) stdout
c) Both stdout and stdin
d) None of the mentioned

7. What happens when we use
fprintf(stderr, “error: could not open filen”);
a) The diagnostic output is directly displayed in the output.
b) The diagnostic output is pipelined to the output file.
c) The line which caused error is compiled again.
d) The program is immediately aborted.

8. Which of the following function can be used to terminate the main function from another function safely?
a) return(expr);
b) exit(expr);
c) abort();
d) Both b and c

Leave a Comment