S.No: 50 Exp.
Name: Write a C program to Delete a File Date:2023-01-16
Aim:
Write a program to delete a file.
Note: Use the remove(fileName) function to delete an existing file.
Source Code:
1 :oN egaP 6240A16K22 :DI
Program1504.c
#include <stdio.h>
void main() {
FILE *fp;
int status;
char fileName[40], ch;
printf("Enter a new file name : ");
gets(fileName);
fp = fopen(fileName,"w"); // Open a new file in write mode
printf("Enter the text with @ at end : ");
while ((ch=getchar())!='@') { // Repeat loop till read @ at the end
putc(ch,fp); // Put read character onto the file
}
putc(ch,fp); // Put delimiter @ at the end on the file
fclose(fp); // Close the file
fp = fopen(fileName,"r"); // Open the existed file in read mode
printf("Given message is : ");
A-ECE-6202-2202 )suomonotuA( gnireenignE dna ygolonhceT fo etutitsnI isaS
while ((ch=getc(fp))!='@') { // Repeat loop till get @ at the end of existed fi
le
putchar(ch); // Put the character on the screen
}
printf("\n");
fclose(fp); // Close the file
status = remove(fileName); // Put the fileName to be removed
if (status == 0)
printf("%s file is deleted successfully\n",fileName ); // Place the removed
fileName
else {
printf("Unable to delete the file -- ");
perror("Error\n");
}
}
Execution Results - All test cases have succeeded!
Test Case - 1
User Output
Enter a new file name : Text1.txt
Enter the text with @ at end : This is CodeTantra@
Given message is : This is CodeTantra
Text1.txt file is deleted successfully
Test Case - 2
User Output
Enter a new file name : Text2.txt
Enter the text with @ at end : C developed by Dennis Ritchie@
Given message is : C developed by Dennis Ritchie
Text2.txt file is deleted successfully
1 :oN egaP 6240A16K22 :DI
A-ECE-6202-2202 )suomonotuA( gnireenignE dna ygolonhceT fo etutitsnI isaS