1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
|
#include <stdio.h>
#include <windows.h>
#include <conio.h>
#include <string.h>
#define MAX 256
int main()
{
int tmp, status;
unsigned options;
FILE *fptr1, *fptr2;
char ch;
char fname[MAX];
char str[MAX], temp[] = "temp.txt";
int lno, ctr = 0;
do
{
system("cls");
printf("\n\t\t\t* Delete a line from file *");
printf("\n\n\n\tChoose an option");
printf("\n\n\n 1. Delete a line from a file");
printf("\n 2. Exit program");
printf("\n\n Select: ");
status = scanf("%d", &options);
while((tmp = getchar()) != EOF && tmp != '\n');
if(!status)
{
printf("\n\n Invalid option.. choose 1 or 2");
Sleep(1500);
options = 0;
continue;
}
else if(options == 1)
{
system("cls");
printf("\n\t\t\t* Delete a line from file *");
printf("\n\n\n\n Enter file name: ");
scanf("%s", fname);
fptr1 = fopen(fname, "r");
printf("\n\n");
while(1)
{
if(!fptr1)
{
printf("\n\n Could not open file");
Sleep(500);
printf("\n\n %s", strerror(errno));
Sleep(1000);
system("cls");
break;
}
ch = getc(fptr1);
for(int lNo = 0; ch != EOF;)
{
ch = 0;
printf(" %i. ", ++lNo);
while(ch != EOF && ch != '\n')
{
printf("%c", ch);
ch = getc(fptr1);
}
printf("\n\n");
}
fptr2 = fopen(temp, "w");
if(!fptr2)
{
printf("\n\n Unable to open a temporary file to write\n");
Sleep(2000);
fclose(fptr1);
break;
}
printf("\n\n Enter the line you want to delete: ");
scanf("%d", &lno);
rewind(fptr1);
ctr = 0;
while(!feof(fptr1))
{
strcpy(str, "\0");
fgets(str, MAX, fptr1);
if(!feof(fptr1))
{
ctr++;
if(ctr != lno)
{
fprintf(fptr2, "%s", str);
}
}
}
fclose(fptr1);
fclose(fptr2);
remove(fname);
rename(temp, fname);
printf("\n\n The line was successfully deleted");
printf("\n\n The contend of the file now is:\n\n");
fptr1 = fopen(fname, "r");
printf("\n\n");
for(lno = 0; fgets(fname, MAX, fptr1) != NULL;)
{
printf(" %i. %s\n", ++lno, fname);
}
Sleep(1000);
printf("\n\n Press any key to return menu..");
getch();
fclose(fptr1);
break;
}
}
else if(options == 2)
{
printf("\n\n\n\n\n\t\t\t\t Exit");
Sleep(1500);
system("cls");
break;
}
else
{
printf("\n\n Invalid option.. choose 1 or 2");
Sleep(1500);
}
}while(options != 2);
return 0;
}
|