0
4.5kviews
Why files are needed? Explain all the file opening modes. Write a program to create copy of a file. Let the user specify names of source and destination files.

Subject : Structured Programming Approach

Title : Pointers and Files

Difficulty : Medium

1 Answer
0
43views

Need of files:

1.When a program is terminated, the entire data is lost.Storing in a file will preserve your data even if the program terminates.

2.If you have to enter a large number of data,it will take a lot of time to enter them all. However if you have a file containing all the data,you can easily access the contents of the file using few commands in c.

3.You can easily move your data from one computer to another without any changes.

4.The various modes in which a file can be opened are as listed below:

i.“r” indicates that the file is to be opened indicates in the read mode.

ii.“w” indicates that the file is to be opened indicates in the write mode.When a file is opened in write mode the data written in the file overwrites the previously stored data in the file.

iii.”a” indicates that the file is to be opened in the append mode.In this mode the data written into the file is appended towards the end of the already stored data in the file.The earlier stored data remains as it is.

iv.“w+” indicates that the file is to be opened in write and read mode.v.“r+” indicates that the file is to be opened in read and write mode.

program to create a copy of file

#include <stdio.h>

#include<conio.h>

#include <stdlib.h>

void main()

{

    char ch, source_file[20], target_file[20];

    FILE *source, *target;

    clrscr();

    printf("Enter name of file to copy\n");

    gets(source_file);

    source = fopen(source_file, "r");

    if( source == NULL )

    {
        printf("Press any key to exit...\n");

        exit(EXIT_FAILURE);

    }

    printf("Enter name of target file\n");

    gets(target_file);

    target = fopen(target_file, "w");

    if( target == NULL )

    {

        fclose(source);

        printf("Press any key to exit...\n");

        exit(EXIT_FAILURE);

    }

    while( ( ch = fgetc(source) ) != EOF )

        fputc(ch, target);

    printf("File copied successfully.\n");

    fclose(source);

    fclose(target);

    getch();

}

Output:

Enter name of file to copy

Factorial.c

Enter name of target file

Factorial-copy.c

File copied successfully
Please log in to add an answer.