Senin, 30 November 2015

File

File is an object on the computer that stores data
There are 2 kinds of file in general:
-Text file (source code, plain text, html files, mosts of configuration files, etc)
-Binary file (mosts audio and video file formats, graphics file formats, compressed files, mosts of office formats, etc)


(-)Type

For files you want to read or write, you need a file pointer:
FILE *fp;

(-)Functions
Reading from or writing to a file in C requires 3 basic steps:
-Open the file.
-Do all the reading or writing.
-Close the file.

-Opening a file:
In order to open a file, use the function fopen(). Use it as:
fp = fopen(filename, mode);

-Reading from or writing to a file:
Once a file has been successfully opened, you can read from it using fscanf() or write to it using fprintf(). These functions work just like scanf() and printf(), except they require an extra first parameter, a FILE * for the file to be read/written.

-Closing a file:
When done with a file, it must be closed using the function fclose().
To finish our example, we'd want to close our input and output files:
fclose(ifp);
fclose(ofp);

=Example=

Write a C program to read name and marks of n number of students from user and store them in a file
#include <stdio.h>
int main(){
   char name[50];
   int marks,i,n;
   printf("Enter number of students: ");
   scanf("%d",&n);
   FILE *fptr;
   fptr=(fopen("C:\\student.txt","w"));
   if(fptr==NULL){
       printf("Error!");
       exit(1);
   }
   for(i=0;i<n;++i)
   {
      printf("For student%d\nEnter name: ",i+1);
      scanf("%s",name);
      printf("Enter marks: ");
      scanf("%d",&marks);
      fprintf(fptr,"\nName: %s \nMarks=%d \n",name,marks);
   }
   fclose(fptr);
   return 0;
}

Tidak ada komentar:

Posting Komentar