PPS Unit 10 Important Programs

Unit 10 - File management

10.1 - Write a program to illustrate the use of fputc ( ) and fputs( ). [W-17, W-19]

#include<stdio.h>

#include<string.h>

int main()

{

    FILE *fp;

    char ch[4]={'a','b','c','d'};

    int i;

    fp=fopen("Test.txt","w");

    if(fp == NULL)

    {

        perror("Error opening file");

        return(-1);

    }

    for(i=0;i<4;i++)

    {

        fputc(ch[i],fp); //use of fputc()

    }

    fputs("EFGH",fp); //use of fputs()

    fclose(fp);

    return 0;

}


10.2 - Write a ‘C’ program to which copies the contents of one file to another. [S-17]

#include <stdio.h>

#include <stdlib.h>

int main()

{

    FILE *fptr1, *fptr2;

    char filename[100], c;

    printf("Enter the filename to open for reading \n");

    scanf("%s", filename);

    fptr1 = fopen(filename, "r");

    if (fptr1 == NULL)

    {

        printf("Cannot open file %s \n", filename);

        exit(0);

    }

    printf("Enter the filename to open for writing \n");

    scanf("%s", filename);

    fptr2 = fopen(filename, "w");

    if (fptr2 == NULL)

    {

        printf("Cannot open file %s \n", filename);

        exit(0);

    }

    c = fgetc(fptr1);

    while (c != EOF)

    {

        fputc(c, fptr2);

        c = fgetc(fptr1);

    }

    printf("\nContents copied to %s", filename);

    fclose(fptr1);

    fclose(fptr2);

    return 0;

}

No comments:

Post a Comment

If you have any doubts or suggestions, Please let me know