Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
5 views

CProgramming_unit5

Uploaded by

kedodop600
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

CProgramming_unit5

Uploaded by

kedodop600
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

Semester-1 B.Tech.

-ESC 103 Introduction


to UNIX and C Programming

Dr. Prakash Kumar


SARALA BIRLA UNIVERSITY
Semester-1 B.Tech.-ESC 103 Introduction to UNIX and C Programming

Module 5

Structures
Structure in c is a user-defined data type that enables us to store the collection of different data types. Each
element of a structure is called a member. Structures ca; simulate the use of classes and templates as it can
store various information

The, struct keyword is used to define the structure.

#include<stdio.h>
#include <string.h>
struct employee
{ int id;
char name[50];
}e1; //declaring e1 variable for structure
int main( )
{
//store first employee information
e1.id=101;
strcpy(e1.name, "SBU");//copying string into char array
//printing first employee information
printf( "employee 1 id : %d\n", e1.id);
printf( "employee 1 name : %s\n", e1.name);
return 0;
}

Array of structures:
An array of structures in C is a data structure that allows you to create an array where each element is a
structure. In other words, it's an array that stores multiple instances of a user-defined structure, with each
element of the array representing one structured data record. This is useful when you want to store and
manage a collection of related data records in a single data structure.

#include <stdio.h>
// Define a structure to represent a person
struct Person {
char name[50];
int age;
};

int main() {
// Declare an array of structures
struct Person people[3];
Semester-1 B.Tech.-ESC 103 Introduction to UNIX and C Programming

// Populate the array of structures


for (int i = 0; i < 3; i++) {
printf("Enter name for person %d: ", i + 1);
scanf("%s", people[i].name);

printf("Enter age for person %d: ", i + 1);


scanf("%d", &people[i].age);
}

// Display the array of structures


printf("\nEntered data:\n");
for (int i = 0; i < 3; i++) {
printf("Person %d: Name: %s, Age: %d\n", i + 1, people[i].name, people[i].age);
}

return 0;
}

Storage classes in C
In C, storage classes define the scope, lifetime, and visibility of variables. C provides several storage classes,
each with specific characteristics. These storage classes are used to control how variables are allocated and
managed in memory. The five main storage classes in C are:

auto (Automatic Storage Class):

 Variables declared as "auto" are automatically allocated storage within the stack memory.
 They have local scope, meaning they are only accessible within the block or function in which they
are defined.
 Their memory is automatically released when the block or function scope ends.

void myFunction() {
auto int x; // Automatic storage class (optional, as it's the default)
}
register (Register Storage Class):

 Variables declared as "register" are stored in CPU registers for faster access.
 The "register" keyword is a request to the compiler to use registers, but the compiler may or may
not honor this request.
 They also have local scope and a short lifetime.

void myFunction() {
register int x; // Register storage class
}
Semester-1 B.Tech.-ESC 103 Introduction to UNIX and C Programming

static (Static Storage Class):

 Variables declared as "static" have a longer lifetime than automatic or register variables.
 They retain their values between function calls and maintain their value throughout the program's
execution.
 They have block scope but are available throughout the program.
 They are initialized to zero by default if not explicitly initialized.

void myFunction() {
static int x; // Static storage class
}

extern (External Storage Class):

 Variables declared as "extern" are not actually allocated memory. They are used to declare a
variable that is defined in another source file.
 They have program scope and are often used to share data between different source files.

extern int x; // External storage class (variable defined in another source file)

Idea of pointers
Pointers in C are variables that store memory addresses. They are a fundamental and powerful concept in
the C programming language. Understanding pointers is crucial for working with data at a low level and for
tasks like memory management, dynamic data structures, and interfacing with hardware.
Declaration and Initialization: Pointers are declared with a specific data type to indicate the type of data
they will point to. They are typically initialized with the memory address of another variable of the same
data type.
#include <stdio.h>

int main() {
int x = 42; // Declare and initialize an integer variable
Semester-1 B.Tech.-ESC 103 Introduction to UNIX and C Programming

int *ptr; // Declare an integer pointer

// Initialize the pointer with the address of the integer variable 'x'
ptr = &x;

// Print the value of the integer variable 'x'


printf("Value of x: %d\n", x);

// Print the value pointed to by 'ptr' (the value of 'x')


printf("Value pointed to by ptr: %d\n", *ptr);

return 0;
}

Self-referential structures, also known as linked structures, are structures in which one of the structure's
members is a pointer to another structure of the same type. This concept is commonly used in building data
structures like linked lists, trees, graphs, and other recursive structures. Pointers play a crucial role in
implementing self-referential structures, as they allow data elements to refer to other elements of the
same structure.
#include <stdio.h>
// Define a self-referential structure for a singly linked list
struct Node {
int data;
struct Node *next; // Pointer to the next node
};
File Handling using built-in functions.
File handling in C is essential for performing tasks such as reading from and writing to files. C provides a
set of built-in functions in the Standard I/O library (stdio.h) to work with files. Here are some commonly
used file handling operations in C:

Opening a File:
To open a file for reading, writing, or appending, you can use the fopen() function. It returns a file pointer
to the opened file.
Reading from a File:

To read data from a file, you can use functions like fread(), fscanf(), and fgets().

Writing to a File:

To write data to a file, you can use functions like fwrite(), fprintf(), and fputs().
Semester-1 B.Tech.-ESC 103 Introduction to UNIX and C Programming

Closing a File:

Always remember to close the file using the fclose() function to release system resources and ensure data
is saved.

Copy the contents of One file to another


(Note: source file must be available in the current directory)
#include <stdio.h>
#include <stdlib.h>

int main() {
FILE *sourceFile, *destinationFile;
char sourceFileName[100], destinationFileName[100];
char ch;

// Input the source file name


printf("Enter the source file name: ");
scanf("%s", sourceFileName);

// Input the destination file name


printf("Enter the destination file name: ");
scanf("%s", destinationFileName);

// Open the source file for reading


sourceFile = fopen(sourceFileName, "r");
if (sourceFile == NULL) {
printf("Failed to open the source file.\n");
exit(1);
}

// Open the destination file for writing


destinationFile = fopen(destinationFileName, "w");
if (destinationFile == NULL) {
printf("Failed to create the destination file.\n");
fclose(sourceFile); // Close the source file before exiting
exit(1);
}

// Copy the contents of the source file to the destination file


while ((ch = fgetc(sourceFile)) != EOF) {
fputc(ch, destinationFile);
}

// Close both files


Semester-1 B.Tech.-ESC 103 Introduction to UNIX and C Programming

fclose(sourceFile);
fclose(destinationFile);

printf("File copy completed.\n");

return 0;
}

Extra Note:
C program to construct a linked list and display
#include <stdio.h>
#include <stdlib.h>

// Define a structure for a singly linked list node


struct Node {
int data;
struct Node* next;
};

// Function to create a new node and return a pointer to it


struct Node* createNode(int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = NULL;
return newNode;
}

// Function to display the elements of the linked list


void displayList(struct Node* head) {
struct Node* current = head;
while (current != NULL) {
printf("%d -> ", current->data);
current = current->next;
}
printf("NULL\n");
}

int main() {
// Initialize an empty linked list
struct Node* head = NULL;

// Create nodes and add them to the list


struct Node* node1 = createNode(10);
struct Node* node2 = createNode(20);
struct Node* node3 = createNode(30);
Semester-1 B.Tech.-ESC 103 Introduction to UNIX and C Programming

// Link the nodes to form a list


head = node1;
node1->next = node2;
node2->next = node3;

// Display the linked list


printf("Linked List: ");
displayList(head);

// Free memory allocated for the nodes


free(node1);
free(node2);
free(node3);

return 0;
}

______eof_Module5______

You might also like