Your code is skipping the first character because you are calling getc()
again after it has already been called to read the 1st letter. You are not doing anything with the first character other than using it to decide whether to enter the loop or not, you are not printing it.
You need to move that 2nd call to getc()
down to the bottom of the loop body, rather than be at the top:
ch = getc(lname);
while (ch != EOF)
{
// ch = getc(lname); <-- move this...
if (ch == '\n')
...
ch = getc(lname); // <-- ... down here instead
}
As for the code printing out ÿ
, that is also due to your 2nd call to getc()
being in the wrong place.
ÿ
has a numeric value of 0xFF
, which is the same value as EOF
when it is treated as a char
. You are not checking the return value of the 2nd call to getc()
until the next loop iteration, after you have already printed ch
regardless of its value.
Your loop should look more like this:
ch = getc(lname);
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, rep);
}
ch = getc(lname);
}
Alternatively, it can be rewritten like this:
while ((ch = getc(lname)) != EOF)
{
if (ch == '\n')
temp++;
//except the line to be deleted
if (temp != delete_line)
{
//copy all lines in file replica.c
putc(ch, rep);
}
}
As for the extra line break, that is because you are printing the '\n'
character that belongs to the "deleted" line. When you encounter a '\n'
character, you increment temp
first, and then evaluate if (temp != delete_line)
to call putc()
. When temp
is equal to delete_line
, you skip putc()
, but when you reach the '\n'
character of delete_line
, you increment temp
first, making if (temp != delete_line)
evaluate as true, so you putc()
the '\n'
character. You need to reverse this logic.
Your final loop code should look more like this instead:
while ((ch = getc(lname)) != EOF)
{
// copy all lines in file replica.c
// except the line to be deleted
if (temp != delete_line)
{
putc(ch, rep);
}
if (ch == '\n')
temp++;
}