C Programming - Input / Output - Discussion

1. 

What will be the content of 'file.c' after executing the following program?

#include<stdio.h>

int main()
{
    FILE *fp1, *fp2;
    fp1=fopen("file.c", "w");
    fp2=fopen("file.c", "w");
    fputc('A', fp1);
    fputc('B', fp2);
    fclose(fp1);
    fclose(fp2);
    return 0;
}

[A]. B
[B]. A
B
[C]. B
B
[D]. Error in opening file 'file1.c'

Answer: Option A

Explanation:

Here fputc('A', fp1); stores 'A' in the file1.c then fputc('B', fp2); overwrites the contents of the file1.c with value 'B'. Because the fp1 and fp2 opens the file1.c in write mode.

Hence the file1.c contents is 'B'.


Vinay said: (Sep 22, 2012)  
The above program cab compiled it gives segmentation faults, please explain.

Shivam said: (Jun 23, 2014)  
Once we've already opened a file in 'w' mode, won't opening it again create some inconsistencies ?

Sol said: (Aug 2, 2015)  
What is the output for:

#include<stdio.h>

int main(){

int arr[][3]={{1,2},{3,4,5},{5}};

printf("%d %d %d", sizeof(arr),arr[0][2],arr[1][2]);

return 0 ;

}

In C the compiler says 36 0 5. Yet there is no such answer in my choices, what other answer could it be?

A Rajasekhar said: (Mar 8, 2016)  
Hi solo,

Here is explanation,

int arr[][3]={{1,2},{3,4,5},{5}};

Here the values in the first inner braces will be the values of Row 0, values in the second braces will be values of row 1 and so on. Now consider this consider this array initialization.

int arr[][3]={ {1,2} , /*row 0*/
{3,4,5}, /*row 1*/
{5}, /*row 2*/
};

arr[0][0]=1; arr[0][1]=2; arr[0][2]=0;
arr[1][0]=3; arr[1][1]=4; arr[1][2]=5;
arr[2][0]=5; arr[2][1]=0; arr[2][2]=0;

So array is 3 rows and 3 columns = arr[3][3];

Then the size of array is 4(for int)*3(row)*3(column) = 36;

arr[0][2]=0; and arr[1][2]=5;

Anusha said: (Oct 11, 2018)  
@Shivam.

No consistencies. We can open the file twice though it is already opened and can write into it. As the file is opened in 'W' mode A is overridden by B.

Post your comments here:

Name *:

Email   : (optional)

» Your comments will be displayed only after manual approval.