Exercise: Input Output

Questions for: Input Output

Which of the following statement is correct about the program?
#include<stdio.h>

int main()
{
    FILE *fp;
    char str[11], ch;
    int i=0;
    fp = fopen("INPUT.TXT", "r");
    while((ch=getc(fp))!=EOF)
    {
        if(ch == '\n' || ch == ' ')
        {
            str[i]='\0';
            strrev(str);
            printf("%s", str);
            i=0;
        }
        else
            str[i++]=ch;
    }
    fclose(fp);
    return 0;
}
A:
The code writes a text to a file
B:
The code reads a text files and display its content in reverse order
C:
The code writes a text to a file in reverse order
D:
None of above
Answer: B

This program reads the file INPUT.TXT and store it in the string str after reversing the string using strrev function.

Which of the following statement is correct about the program?
#include<stdio.h>

int main()
{
    FILE *fp;
    char ch;
    int i=1;
    fp = fopen("myfile.c", "r");
    while((ch=getc(fp))!=EOF)
    {
        if(ch == '\n')
            i++;
    }
    fclose(fp);
    return 0;
}
A:
The code counts number of characters in the file
B:
The code counts number of words in the file
C:
The code counts number of blank lines in the file
D:
The code counts number of lines in the file
Answer: D

This program counts the number of lines in the file myfile.c by counting the character '\n' in that file.

Point out the error/warning in the program?
#include<stdio.h>

int main()
{
    unsigned char ch;
    FILE *fp;
    fp=fopen("trial", "r");
    while((ch = getc(fp))!=EOF)
        printf("%c", ch);
    fclose(fp);
    return 0;
}
A:
Error: in unsigned char declaration
B:
Error: while statement
C:
No error
D:
It prints all characters in file "trial"
Answer: A
Here, EOF is -1. As 'ch' is declared as unsigned char it cannot deal with any negative value.
Point out the error in the program?
#include<stdio.h>

/* Assume there is a file called 'file.c' in c:\tc directory. */
int main()
{
    FILE *fp;
    fp=fopen("c:\tc\file.c", "r");    
    if(!fp) 
      printf("Unable to open file.");        

    fclose(fp);
    return 0;
}
A:
No error, No output.
B:
Program crashes at run time.
C:
Output: Unable to open file.
D:
None of above
Answer: C
The path of file name must be given as "c:\\tc\file.c"
Point out the error in the program?
#include<stdio.h>

int main()
{
    FILE *fp;
    fp=fopen("trial", "r");
    fseek(fp, "20", SEEK_SET);
    fclose(fp);
    return 0;
}
A:
Error: unrecognised Keyword SEEK_SET
B:
Error: fseek() long offset value
C:
No error
D:
None of above
Answer: B
Instead of "20" use 20L since fseek() need a long offset value.
Ad Slot (Above Pagination)
Quiz