Assignment 6
Assignment 6
1.What is a structure?
Ans: A structure is a collection of logically related variables of different data types
under a single name.
2.What is a file?
Ans. A file is a complex data type that is stored externally to the main memory,
usually on disk. In other words we can say, it is a storage area of memory, where
the data are stored in an organized form.
3.Define nested structure
Ans. when a structure is placed within another structure, as its member, then the
resultant structure is called nested structure.
4.write the syntax to open a file
Ans. Syntax: FILE *fp;
Fp=fopen(“file_name” mode);
Part-B
1.write any four differences between structure and union
S. No Structure Union
2. Every member has its own memory All the members use the same
space. memory space to store the values.
3. Keyword struct is used. Keyword union is used.
Part-C
1.Write a C program to implement nested structure.
#include <stdio.h>
// Define sub-structures
struct Address {
char street[50];
char city[50];
char state[20];
int zip;
};
struct DateOfBirth {
int day;
int month;
int year;
};
// Define high-level structure containing nested structures
struct Person {
char name[50];
int age;
struct Address address;
struct DateOfBirth dob;
};
int main() {
// Declare and initialize a person
struct Person person1 = {
.name = "John Doe",
.age = 30,
.address = {"123 Main St", "Anytown", "CA", 12345},
.dob = {10, 5, 1994}
};
// Print person's information
printf("Name: %s\n", person1.name);
printf("Age: %d\n", person1.age);
printf("Address: %s, %s, %s, %d\n", person1.address.street,
person1.address.city, person1.address.state, person1.address.zip);
printf("Date of Birth: %d/%d/%d\n", person1.dob.month, person1.dob.day,
person1.dob.year);
return 0;
}Output:
Name: John Doe
Age: 30
Address: 123 Main St, Anytown, CA, 12345
Date of Birth: 5/10/1994
7.Write a c program to create a text file and print contents of the file in
reverse order using fseek ()and ftell ()functions.
#include <stdio.h>
#include <stdlib.h> // For exit()
int main() {
FILE *fptr;
char filename[100], c;
printf("Enter the filename to open: ");
scanf("%s", filename);
// Open file for reading
fptr = fopen(filename, "r");
if (fptr == NULL) {
printf("Cannot open file.\n");
exit(0);
}// Read contents from file
c = fgetc(fptr);
while (c != EOF) {
printf("%c", c);
c = fgetc(fptr);
}
fclose(fptr);
return 0;}