C Code Snippets 10 - File Operations



Hello everyone,

A file represents a sequence of bytes, regardless of it being a text file or a binary file. C programming language provides access on high level functions as well as low level (OS level) calls to handle file on your storage devices. 



This code snippet will show you how to create a small class list with their names, grades and numbers.



/**
* Author : Berk Soysal
*/

#include <stdio.h>
#include <stdlib.h>

int main()
{
    FILE *file;           /* file pointer */
    const int n = 3;   /* number of students    */
    char  name[10];
    int   id, grade, i=0;

    /* open the file */
    file = fopen("student.txt", "w"); // Has to be in the same directory as .c file

    if( file == NULL )
    {
      printf("Cannot open ""student.txt"" !\n"); exit(1);

    }

    printf("Enter the student information:\n\n");

    while( i++<n )  // check the condition first and then increment i
    {
      printf("%d. Student Number     : ",i); scanf("%d",&id);
      printf("%d. Name of the Student: ",i); scanf("%s",name);
      printf("%d. Grade              : ",i); scanf("%d",&grade);
      printf("\n");

      fprintf(file,"%5d %10s %3d\n",id,name,grade); /* write into the file */
    }

    /* close the file */ /* very important !! */
    fclose(file);

    printf("Information has been saved!\a");

 return 0;
}


Output
 

The file has been saved to the same directory as our .exe file. When we open the saved students.txt file;



Keywords: CCode Snippets
Author:

Software Developer, Codemio Admin

Disqus Comments Loading..