User Tools

Site Tools

Return to Home page

File writing (Example 1)

Function for open, close and write data into a file.

Implement a C program that:

  • fills a vector of structures, where each element of the vector is a structure that contains a vector of characters containing the name of a student, a variable of type unsigned int containing a student identifier and a variable of type float containing the average value of the scores of the exams attended by the student
  • opens a file with name out.txt for writing the data stored in the vector of structures
  • writes in the file the content of the vector of structures previously filled (a record/element of the vector for each row of the file)
  • closes the file


/* Example about the functions useful to write some data into a file */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define LEN 50
#define N_STUD 2
/* Definition of a new type stud_t */
typedef struct stud{
  char name[LEN+1];
  unsigned int student_id;
  float average;
int main() {
  FILE *fp;
  stud_t students[N_STUD];
  int i;
  char row[LEN+1];
  /* Filling of the first two records of the vector of type stud_t */
  strcpy(students[0].name, "Jules");
  students[0].student_id = 122333;
  students[0].average = 23.5;
  strcpy(students[1].name, "Laia");
  students[1].student_id = 122334;
  students[1].average = 29.5;
  /* Opening the file for write */
  fp = fopen("out.txt", "w");
  if (fp == NULL){
    printf("Error: impossible to open the file out.txt\n");
  /* Write data into the file: first method using the function fprintf */
  fprintf(fp, "First writing method\n"); /* Recommended */
  for(i=0; i<N_STUD; i++){
    fprintf(fp, "%s %d %f\n", students[i].name, students[i].student_id, students[i].average);
  /* Write data into the file: second method using the function fputs */
  fputs("Second writing method\n", fp);
  for(i=0; i<N_STUD; i++){
    sprintf(row, "%s %d %f\n", students[i].name, students[i].student_id, students[i].average);
    fputs(row, fp);
    fclose(fp); /* Closing the file */
  return 0;

If you found any error, or if you want to partecipate to the editing of this wiki, please contact: admin [at]

You can reuse, distribute or modify the content of this page, but you must cite in any document (or webpage) this url:
/web/htdocs/ · Last modified: 2024/04/08 22:35 by

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki
Privacy Policy