Reputation:
I found a code on the internet that is used to delete a specific line in a .txt file. The issue is that it also deletes the first character of the file. For example: contents in the txt file-
test line 1
test line 2
test line 3
test line 4
contents after deleting the 2nd line-
est line 1
test line 3
test line 4
The code from the website can be found here.
The code is:
/*
* C Program Delete a specific Line from a Text File
*/
#include <stdio.h>
int main()
{
FILE *fp1, *fp2;
char filename[100];
char filename2[100];
char ch;
int delete_line, temp = 1;
printf("Enter file name: ");
scanf("%s", filename);
sprintf(filename2, "%s.txt", filename);
//open file in read mode
fp1 = fopen(filename2, "r");
ch = getc(fp1);
while (ch != EOF)
{
printf("%c", ch);
ch = getc(fp1);
}
//rewind
rewind(fp1);
printf(" \n Enter line number of the line to be deleted:");
scanf("%d", &delete_line);
//open new file in write mode
fp2 = fopen("replica.c", "w");
ch = getc(fp1);
while (ch != EOF)
{
ch = getc(fp1);
if (ch == '\n')
temp++;
//except the line to be deleted
if (temp != delete_line)
{
//copy all lines in file replica.c
putc(ch, fp2);
}
}
fclose(fp1);
fclose(fp2);
remove(filename2);
//rename the file replica.c to original name
rename("replica.c", filename2);
printf("\n The contents of file after being modified are as follows:\n");
fp1 = fopen(filename2, "r");
ch = getc(fp1);
while (ch != EOF)
{
printf("%c", ch);
ch = getc(fp1);
}
fclose(fp1);
return 0;
}
Upvotes: 0
Views: 261
Reputation: 22
You are calling getc() two times in your second loop so the first char that you are evaluating is the second one of the file.
You simply have to call getc() at the end of the loop like so :
ch = getc(fp1);
while (ch != EOF)
{
if (ch == '\n')
temp++;
//except the line to be deleted
if (temp != delete_line)
{
//copy all lines in file replica.c
putc(ch, fp2);
}
ch = getc(fp1);
}
Upvotes: 0