Structure and file processing

Structure
Structure is a data type used to store a group of data. It is user defined and the group of data can be varied.
Structure declaration :
struct name_structure{
   data_type name
   ...
};

Example :
struct mahasiswa{
   int NIM;
   char nama[21];
   char jurusan[51];
}agus;

To call an element of a structure, use dot operator : agus.NIM
Structure can also be used in conjunction with array. To declare structrure with array, just declare it as usual.

struct mahasiswa{
   int NIM;
   char nama[21];
   char jurusan[51];
}data[20];

Example of storing structured array:
void storeStruct(){
   struct mahasiswa{
      int NIM;
      char nama[21];
      char jurusan[51];
   }data[20];
   
   int i;

   for(i = 0; i < 20; i++){
        scanf("%d", &data[i].NIM);
        scanf("%[^\n]", &data[i].nama);
        getchar();
        scanf("%[^\n]", &data[i].jurusan);
        getchar();   
   }
}

File Processing
To open a file in C, you need a pointer in your program. In C, they use File *name for using file.
Example : File *fin 

There are several mode in C, but the most common are :
- w, create a file/overwrite a file
- r, read a file
- a, to modify a file

The function for file processing is the same as others, except you add f in front of the function(fscanf,fprintf).

There are 3 steps in processing a file :
- Opening the file
   File *fin = ("file name", "mode");
   Example = File *fin = ("textdata.in", "r");

- Processing the file
   Example of reading file

int x;
   while(!feof(fin)){
        fscanf(fin, "%d\n", &x);
   }

- Closing the file
   fclose(fin);





Comments