In: Computer Science
*Answer in C program*
#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;
}
#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;
}
1. In the above program, the statement: fp1= fopen
("C:\\myfiles\\newfile.txt", "r") will open the file in read
mode.
2. Syntax for opening a file: *fp = FILE *fopen(const char *filename, const char *mode); Here, *fp is the FILE pointer ( FILE *fp ), which will hold the reference to the opened(or created) file.
3. The mode being used is read mode. example: fp1= fopen ("C:\\myfiles\\newfile.txt", "r"); The 'r' specifies that file is opened in read mode.
4. With reference to the above program, the file pointer fp1 holds the reference to the opened or created file.
5. If the file is successfully opened, then the file pointer fp1 will hold the reference of the created file. If it is not opened,then file pointer will hold NULL.
6. //Code that will check the file has opened
successfully:
if (fp1 == NULL) {
perror("ERROR: ");// here perror will print the error
return 1;
}
7. To read a file, the function to be used is fgetc() or fgets(). It reads upto n-1 characters. If the file is a binary type of file, then the function used to read that file is fread();
8. To write in a file, first, the file should be opened in write mode("w"). Then we use the function fputc() to write individual characters to the stream or fputs() to write string to the file.
/*C program to write in the file*/
#include <stdio.h>
int main() {
FILE *fp;
fp = fopen("sample.txt", "w");
fputs("This is testing for fputs...\n", fp);
fclose(fp);
return 0;
}
9. The function used for closing the file is fclose(); This would
close the file associated with the file pointer.
10. //Program that contains open, read, write and close
operation in C.
#include <stdio.h>
int main()
{
FILE * fp;
char c;
// to open a file in write mode
fp = fopen("sample.txt", "w");
//writing operation on the file sample.txt character by
character
while ((c = getchar()) != EOF) {
putc(c, fp);
}
//to close the file
fclose(fp);
printf("Data Entered in the file:\n");
//to open the file for reading
fp = fopen("sample.txt", "r");
while ((c = getc(fp)) != EOF) {
printf("%c", c);
}
fclose(fp);// to close the file which is opened
return 0;
}
11. To read strings in files, we use the function fgets() and to write in the file, we use fputs().
12. //Program to read the strings from a file in C
programming.
#include <stdio.h>
#define maxCharacter 1000
int main() {
FILE *fp;
char s[maxCharacter];
char* name = "c:\\temp\\demo.txt";
fp = fopen(name, "r");
if (fp == NULL){
printf("Could not open file %s",name);
return 1;
}
while (fgets(s, maxCharacter, fp) != NULL)
printf("%s", s);
fclose(fp);
return 0;
}