AnkitWebLogic

Delete line | File handling

Exercise 7. WAP to delete line from a file. 1

#include<stdio.h>
int main()
{
    FILE *fp, *fp2;
    int line, n=1;
    char text[80];
    fp=fopen("file.txt","r");
    if (!fp) //check if file exists
    {   
        printf("File not found!");
        return 0; //terminates the program
    }
    fp2=fopen("temp.txt","w");
    printf("Enter line no. to delete: ");
    scanf("%d",&line);
    do{
        fgets(text,80,fp); //read line from file
        if(n!=line) //skip the line to delete
            fputs(text,fp2); //write line in file
        n++;
    }while(!feof(fp));
    fclose(fp);
    fclose(fp2);
    remove("file.txt");
    rename("temp.txt","file.txt");
    return 0;
}
Enter line no. to delete: 2
file.txt - before program execution
first line
second line
third line
file.txt - after program execution
first line
third line

Advertisement

Advertisement