UNIT-V PROGRAMS

Unit-V: Dynamic Memory Allocation & File Handling Operations

1. Program to Copy Content of One File into Another

  • Purpose: To copy contents from one file (Input.txt) to another.

  • Code:

    #include <stdio.h>
    int main(){  
        FILE *fptr1, *fptr2;  
        char c;  
        // Open one file for reading  
        fptr1 = fopen("Input.txt", "r");  
        fptr2 = fopen("filename", "w");  
        // Read contents from file  
        c = fgetc(fptr1);  
        while (c != EOF){   
            fputc(c, fptr2);   
            c = fgetc(fptr1);  
        }  
        fclose(fptr1);  
        fclose(fptr2);  
        return 0;  
    }

2. Program to Count Number of Words and Characters in a File

  • Purpose: To calculate total characters, words, and lines in test.txt.

  • Code:

    #include <stdio.h>
    int main() {  
        FILE *file;   
        char ch;  
        int characters, words, lines;  
        /* Open source files in 'r' mode */   
        file = fopen("test.txt", "r");  
        characters = words = lines = 0;  
        while ((ch = fgetc(file)) != EOF) {  
            characters++;  
            /* Check new line */  
            if (ch == '\n' || ch == '\0')  
                lines++;  
            /* Check words */  
            if (ch == ' ' || ch == '\t' || ch == '\n' || ch == '\0')  
                words++;  
        }  
        /* Increment words and lines for last word */   
        if (characters > 0) {  
            words++;  
            lines++;  
        }  
        /* Print file statistics */  
        printf("\n");  
        printf("Total characters = %d\n", characters);  
        printf("Total words  = %d\n", words);  
        printf("Total lines  = %d\n", lines);  
        /* Close files to release resources */   
        fclose(file);   
        return 0;  
    }

3. Program to Implement malloc()

  • Purpose: To allocate memory dynamically for n integers.

  • Code:

    #include<stdio.h>  
    #include<stdlib.h>  
    void main() {  
        int *ptr, n, i;  
        printf("Enter how many numbers you want to enter");  
        scanf("%d", &n);  
        ptr = (int *) malloc(n * sizeof(int));  
        for (i=0; i<n; i++) {  
            scanf("%d", ptr+i);  
        }  
        for (i=0; i<n; i++) {  
            printf("%d", *(ptr+i));  
        }  
    }

4. Program to Implement calloc()

  • Purpose: To allocate memory dynamically and initialize memory to zero for n integers.

  • Code:

    #include<stdio.h>  
    #include<stdlib.h>  
    void main() {  
        int *ptr, n, i;  
        printf("Enter how many numbers you want to enter");  
        scanf("%d", &n);  
        ptr = (int *) calloc(n , sizeof(int));  
        for (i=0; i<n; i++) {  
            scanf("%d", ptr+i);  
        }  
        for (i=0; i<n; i++) {  
            printf("%d", *(ptr+i));  
        }  
    }