IN C: Please help come up with example for the following question. 1.) Given a s
ID: 3834047 • Letter: I
Question
IN C: Please help come up with example for the following question.
1.) Given a struct definition, write code to do the following:
a.) Declare a variable of that type.
b.) Declare an array of that type.
c.) Initialize the elements of the variable in part a) using the dot operator.
d.) Initialize one of the elements of the array created in part b).
e.) Write a function call which passes the struct variable from part a).
f.) Write the function heading for the function from part e).
2. Write code to do the following:
a.) Open a file for input or output
b.)Read from or write to this file
c.) Close this file
Explanation / Answer
#include<stdio.h>
//Assume input.txt contains data. A sample line 2 Miller (first entry is id and second is name). Let the output
//file name is output.txt
//Given a struct definiton:
struct Student {
int id;
char name[10];
};
void disp(struct Student data);
void disp(struct Student data){
printf("%d %s ", data.id, data.name);
}
void main(){
FILE *fin, *fout;
int id;
char name[10];
struct Student stu1; //Declaring a variable of that typoe
struct Student stu_list[10];
stu1.id = 1;
stu1.name = "John";
stu_list[0].id = 2;
stu_list[0].name = "Mary"
disp(stu1);
fin = fopen("input.txt", "r");
fout = fopen("output.txt", "w");
if (fin != NULL && fout != NULL){
while (fscanf(fin, "%d %s", &id, name) != EOF){
fprintf(fout, "%d %s ", id, name);
}
fclose(fin);
fclose(fout);
}
else {
if (fin == NULL)
printf("Error opening input.txt ");
if (fout == NULL)
printf("Error opening output.txt ");
}
}