Various file opening modes in C:
Below are the three basic modes for opening a file.
1. Read mode
2. Write mode
3. Append mode
Read mode:
This mode opens an existing file for reading. If the given file does not exists, it returns NULL to the file pointer.
Syntax:
FILE *fp;
fp = fopen("filename.txt", "r");
if (fp == NULL)
printf("The given file name does not exists\n");
where "filename.txt" is the file name and "r" is the mode(read mode).
Write mode:
This mode opens a new file on the disk for writing. If a file already exists with the given file name, then this mode will overwrite the file.
Syntax:
fp = fopen("write.txt", "w");
where "write.txt" is the file name and "w" is the mode.
Append mode:
This mode opens a preexisting file for appending data. If the file does not exist, it opens a new file for write operation.
Syntax:
fp = fopen("append.txt", "a");
where "append.txt" is the file name and "a" is the mode.
Below are few other file opening modes available in C language.
Example C program on file opening modes:
#include <stdio.h>
int main() {
char ch;
FILE *fp;
fp = fopen("write.txt", "w");
while((ch = getchar()) != EOF) {
fputc(ch, fp);
}
fclose(fp);
fp = fopen("write.txt", "r");
printf("\nContents of the file write.txt\n");
while ((ch = fgetc(fp)) != EOF) {
putchar(ch);
}
fclose(fp);
fp = fopen("write.txt", "a");
fprintf(fp, "Appending hello world in write.txt\n");
fclose(fp);
printf("\n\nContents of write.txt after append operation\n");
fp = fopen("write.txt", "r");
printf("Contents of the file write.txt\n");
while ((ch = fgetc(fp)) != EOF) {
putchar(ch);
}
fclose(fp);
return 0;
}
Output:
jp@jp-VirtualBox:~/$ ./a.out
I am writing into a file named write.txt
Here are the contents... Hello world
I am fine... How are you?
Contents of the file write.txt
I am writing into a file named write.txt
Here are the contents... Hello world
I am fine... How are you?
Contents of write.txt after append operation
Contents of the file write.txt
I am writing into a file named write.txt
Here are the contents... Hello world
I am fine... How are you?
Appending hello world in write.txt
I am writing into a file named write.txt
Here are the contents... Hello world
I am fine... How are you?
Contents of the file write.txt
I am writing into a file named write.txt
Here are the contents... Hello world
I am fine... How are you?
Contents of write.txt after append operation
Contents of the file write.txt
I am writing into a file named write.txt
Here are the contents... Hello world
I am fine... How are you?
Appending hello world in write.txt
No comments:
Post a Comment