This blog is under construction

Sunday, 20 May 2012

What is a file in C language

A file is a resource to store set of related information permanently on a computer disk.  C language facilitates the user to access or modify file contents using a set of library functions.

Below are the sequence of file operation which needs to be followed to access or modify file contents.
1.  Opening a file
2.  Reading or writing a file
3.  Closing a file

Example C program to write a string into a file:

  #include <stdio.h>
  int main() {
        FILE *fp;
        // opening file.txt in write mode
        fp = fopen("file.txt", "w");
        if (fp == NULL) {
                printf("Unable to open the given file\n");
        // writing hello world to the file
        fputs("hello world\n\n", fp);
        // Close the opened file
        fclose (fp);
        return 0;

  jp@jp-VirtualBox:~/$ ./a.out
  jp@jp-VirtualBox:~/$ cat file.txt
  hello world

No comments:

Post a Comment