Senin, 10 Desember 2018

File Processing

File and Streams
-When a C  program run, there a three standard streams activated :
1.Standard Input Stream
2.Standard Output Stream
3.Standard Error Stream

File Definition:
File is a collection of record.Record is a collection of field.Field is a block of byte.Byte is  collection of bit.


Open File
-Opening a File using fopen():
a. File *fopen ( const char *filename, const char *mode);
b. fopen() defined at <stdio.h>
c. fopen() return a pointer to the start of a buffer area. Null will be returned if file unable to open.

- Possible mode value:
   Mode                 Description
a. "r"                    opening a file to be read.
b. "w"                   creating a file to be written.
c. "a"                     opening a File for data append.

Close File
-Closing a File using fclose():
 a. int fclose (File *stream);

Example writing data to file text.txt using fprintf:
#include <stdio.h>int main(void)
{    FILE *fp;
    fp=fopen("test.txt","w");    if(fp==NULL){        printf("File test.txt can’t be created\n");        exit(1);    }    fprintf(fp,"%d %s %f\n",1,“Amir", 3.95);    fprintf(fp,"%d %s %f\n",2,“Tono", 3.15);    fclose(fp);    return 0;
}


Example writing data to file text.txt using fscanf:

#include <stdio.h>
int main(void)
{
  FILE *fp;  int no; char name[20]; float gpa;
  fp=fopen("test.txt","r");
  if(fp==NULL){
  printf("File test.txt can’t be opened\n");   exit(1);
  }
  fscanf(fp,"%d %s %f",&no,name, &gpa);
  printf("%d %s %f\n",no,name,gpa);
  fscanf(fp,"%d %s %f",&no,name, &gpa);
  printf("%d %s %f\n",no,name,gpa);
  fclose(fp);     return 0;
}

Example writing data to file text.txt using fwrite:


#include <stdio.h>
int main(void)
{
    FILE *fp;
    int Arr[]={1,2,3,4,5};
    fp=fopen("test.dat","w");
    if(fp==NULL){
        printf("File test.dat can’t be created\n");
        exit(1);
    }
    fwrite(Arr,sizeof(Arr),1,fp);
    fclose(fp);
    return 0;
}


 




Tidak ada komentar:

Posting Komentar