Write a program to remove line (entered line number) from the file.
#include<stdio.h> #include<stdlib.h> #include<string.h> #include"fileinfo.h" void Delete_Line_of_File(FILE*,int,char*); int main() { char fileName[50],ch; FILE *fp; int DeleteLineOfNumber; printf("Enter file name : "); scanf("%s",fileName); fp = fopen(fileName,"r+"); if(fp == NULL) { printf("%s File is not present in this directory\n",fileName); return 0; } printf("Which Line Do you want to delete = "); scanf("%d",&DeleteLineOfNumber); Delete_Line_of_File(fp,DeleteLineOfNumber,fileName); return 0; } void Delete_Line_of_File(FILE *fp,int LineNum,char* file) { char **ptr,temp[100]; int i,LineCount,StrMaxLen; LineCount = Get_Total_Lines(fp); if(!(LineNum >= 1 && LineNum <= LineCount)) { printf("Invalid Line Number\n"); fclose(fp); return; } LineNum--; ptr = (char**)malloc(sizeof(char*)*LineCount); StrMaxLen = Get_Max_String_Length(fp); for(i = 0; i < LineCount;i++) { ptr[i] = (char*)malloc(StrMaxLen+1); } for(i=0;i < LineCount;i++) { fgets(ptr[i],StrMaxLen+1,fp); } fclose(fp); fp = fopen(file,"w"); for(i=0;i<LineCount;i++) { if(i != LineNum) { fputs(ptr[i],fp); } } fclose(fp); printf("Deleting Done....\n"); }
Note: File name data is present in the current working directory.
cat data Lot To Learn BlackBerry Iphone Incredible India
Output
Enter file name : data Which Line Do you want to delete = 2 Deleting Done....
cat data Lot To Learn Iphone Incredible India