This blog is under construction

Sunday, 20 May 2012

Different file opening modes in c

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.
 w+  Open for reading and writing. The file is created if it doesn't exist, otherwise it is truncated. The stream is positioned at the beginning of the file.
 r+  Open for reading and writing. The stream is positioned at the beginning of the file.
 a+  Open for reading and appending (writing at end of file). The file is created if it does not exist. The initial file position for reading is at the beginning of the file, but output is always appended to the end of the file.


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




No comments:

Post a Comment