Syntax for opening a file:
File is opened with the following statements:
FILE *fp;
fp = fopen("file_name", "mode");
where fp is a file pointer, mode is the file opening mode(read, write or append) and file_name is the name of the file to be opened.
fopen() performs the following tasks for opening a file:
- It searches for the specified file in the disk to open it.
- If the given file is available in disk, then the file will be moved to memory. If not, NULL is returned to the file pointer.
- It locates the character pointer to point to the first character of the file.
Syntax for closing a file:
File is closed using the following statement.
fclose(file_pointer);
The above statement closes the file associated with the file pointer file_pointer.
Example program to illustrate opening and closing files in C
#include <stdio.h>
int main() {
// file pointer => fp
FILE *fp;
char ch, str[100];
// opening the file input.txt in write mode
fp = fopen("input.txt", "w");
while((ch = getchar()) != EOF) {
fputc(ch, fp);
}
// closing the file
fclose(fp);
// opening input.txt in read mode
printf("\n\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n");
printf("\tContents in input.txt\n");
printf("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n");
fp = fopen("input.txt", "r");
while((ch = fgetc(fp)) != EOF) {
fputc(ch, stdout);
}
// closing the file
fclose(fp);
return 0;
}
Output:
jp@jp-VirtualBox:~/$ ./a.out // writing below contents in input.txt
hello world
hello world
hello world
hello world
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Contents in input.txt
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
hello world
hello world
hello world
hello world
hello world
hello world
hello world
hello world
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Contents in input.txt
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
hello world
hello world
hello world
hello world
In the above program, we have written "hello world" 4 times in input.txt and prints the contents of the same file in output screen.
No comments:
Post a Comment