In: Computer Science
#include <stdio.h>
int main()
{
FILE *fp1;
char c;
fp1= fopen ("C:\\myfiles\\newfile.txt", "r");
while(1)
{
c = fgetc(fp1);
if(c==EOF)
break;
else
printf("%c", c);
}
fclose(fp1);
return 0;
}
Answer
here is your answer if you have any doubt please comment, i am here to help you.
*In the program above which statement is functioning for opening a file ,Write the syntax for opening a file?
Here,
fp1= fopen ("C:\\myfiles\\newfile.txt", "r");
this line is the opening a file for reading mode. where fp1 is the file handler or file pointer. using fopen() method we can open any file in c. Here is the syntax for opening a file.
fopen(filename,mode)
// where mode is r-read, w-write, a,r+,w+
*What mode that being used in the program. Give the example from the program?
i already said that the above problem , file opened for read mode. Thats why 'r' is used.
Other modes are,
*Referring to the program above what has been stored in the pointer fp1.?
fp1 is a special pointer called File pointer is used which is declared as FILE *fp1;. which is used to handle and keep track on the files being accessed. You must use stdio.h header file for this.
*Explain how to check whether the file has opened successfully?
*Write code that will check the file has opened successfully.
if ( fp1 == NULL )
{
printf( "Failed to open." ) ;
}
you can use this code, because the file opened successfully, the file pointer must have value, not null, if it is null then ,we can say the file is not opened successfully.
Explain the function that can be used to read a file?
In this above code, each character is reading from the text file using while loop. Here is the code for printing the value from the text file.
while(1)
{
c = fgetc(fp1); //file pointer will update each iteration
if(c==EOF) //if file pointer will end of the file the loop will break
break;
else
printf("%c", c);
}
output of the above code.
I answered 4 sub question here , and any doubt please comment,
thanks in advance