Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write two programs to write and read from file the age and first and last names

ID: 3573109 • Letter: W

Question

Write two programs to write and read from file the age and first and last names of people. The programs should work as follows The first program reads strings containing first and last names and saves them in a binary file (this should be done with the fwrite function). The program should take the name of the tile as a command line argument The loop ends when the user enters an empty siring (new line): This program reads and saves ages and names in a binary file. Enter person (age, name):40, John Smith Enter person (age, name):32, Bill Jones Enter person (age, name): The second program reads in from the binary file above (with the fread function) and prints out the ages and names on the screen The program should take the name of the file as a command line argument. program prints ages and names from a binary file. Name: 40, John Smith Name: 32, Bill Jones

Explanation / Answer

#define _CRT_SECURE_NO_WARNINGS

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

#define SIZE 1

int main(){
   char line[100];
   FILE *fp = fopen("data.bin", "w");
   printf("This program reads and saves ages and name in a binary file. ");
   while(1){
       printf("Enter person (age, name): ");
       gets(line);
       if(strlen(line) == 0)
           break;
       printf("%s ", line);
       fwrite(line, 1, strlen(line), fp);
       fwrite(" ", 1, 1, fp);
   }
   fclose(fp);
   return 0;
}


#define _CRT_SECURE_NO_WARNINGS

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

#define SIZE 1

int main(){
   char line[100];
   FILE *fp = fopen("data.bin", "r");
   if(fp){
       while(fread(line, 1, 100, fp)){
           printf("Person: %s ", line);
       }
       fclose(fp);
   }
   return 0;
}