In: Computer Science
#include
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;
}
please answer all
1)The statement fp1= fopen ("C:\\myfiles\\newfile.txt", "r"); is for opening the file newfile.txt from the path C:\\myfiles.
2)The general Syntax for opening a file is
FILE *ptr ///declaring the pointer to ensure effective cconnection and communication between the program and the file.
fopen("file path", "mode"); /// filepath is the loaction of the file in the system eg:C:\\myfiles\\newfile.txt as in the given program. Mode is in which mode the file opens in the programme.the most common modes are r(read) and w(write).
3)In the given program the mode used is 'r' i.e., it opens the file in read mode. The contents of the file can be read.
eg: fp1= fopen ("C:\\myfiles\\newfile.txt", "r");
4)The pointer fp(*fp1) stores the information regarding the file we are currently handling. This pointer acts as a link between the programme and file.
5)We can check if the file opened succesfully by giving a if function for checking the vakue of the declared pointer is NULL or not
6)eg: if(fp1==NULL) //then not opened succesfully.
7)The function for reading a file is fopen("filename","mode") where mode is r that is for read.
8)To write a file the function is fopen("filename","w") where w indicated write mode.
int main()
{
FILE *fp1;
fp1= fopen ("C:\\myfiles\\newfile.txt", "w");
if(fp1== NULL){
printf("error"); // not opened succesfully
exit(1);
}
int n= 10;
fprintf(fp1,"%d",n);
fclose(fp1);
return (0);
}
9)fclose(pointer) is used to close a file, where pointer is the file pointer name.
10)int main()
{
FILE *fp1,*fp2;
char c;
fp1= fopen ("C:\\myfiles\\newfile.txt", "r");
while(1)
{
c = fgetc(fp1);
if(c==EOF)
break;
else
printf("%c", c);
}
fp2= fopen ("C:\\myfiles\\newfile1.txt", "w");
if(fp1== NULL){
printf("error"); // not opened succesfully
exit(1);
}
int n= 10;
fprintf(fp2,"%d",n);
fclose(fp1);
fclose(fp2);
return 0;
}
11)fgets(char *s, int len, FILE *fpr) is used to read a string from a file.
s= array of characters to store the string, len= length of input, fpr= pointer to the file.
fputs(char *s, FILE *fpr) is used to write to a file.
s= array, fpr= pointer to the file.
12)
int main()
{
FILE *fr,*fw;
/*array to store string */
char str[100];
/*Opening the file in "r" mode*/
fr = fopen("C:\\readfile.txt", "r");
/*Opening the file in "w" mode*/
fw = fopen("C:\\writefile.txt", "w");
/*Error handling*/
if (fr == NULL || fw == NULL)
{
printf("error");
}
/*reading the file till end*/
while(1)
{
if(fgets(str, 10, fr) ==NULL)
break;
else
printf("%s", str);
}
/* writing to file*/
fputs(str,fw);
/*Closing the input file after reading*/
fclose(fr);
/*Closing the input file after writing*/
fclose(fw);
return 0;
}