This code snippet is working the first while loop but is not executing the one after it

73 views Asked by At

This code is supposed to skip a line of file and write everything else in a different file, delete the original one, and rename the different one to the one deleted. Whats wrong with this code is its not working after the first file ,i.e., the second file it is niether deleted nor a new file is created with the skipped line of file. what is the issue? Does it has to do something with the rename remove function?

FILE *lname
FILE *id
FILE *rep

lname = fopen("lname.txt", "r");
id = fopen("id.txt", "r");
rep = fopen("rep.txt", "w+");

char ch1,ch2;
int temp=1,delete_line=3; /*(delete_line is supposed to be taken as an input)*/

ch1 = getc(lname);

while (ch1 != EOF)
{
    if (ch1 == '\n')
        temp++;

    if(delete_line==1) {
        if (temp == 2 && ch1 == '\n')
            ch1 = getc(lname);
    }

    if (temp != delete_line)
        putc(ch1, rep);
​
    ch1 = getc(lname);
}

fclose(lname);
fclose(rep);

remove("lname.txt");
rename("rep.txt","lname.txt");

rep = fopen("rep.txt", "w+");
​
ch2 = getc(id);

while (ch2 != EOF)
{
    if (ch2 == '\n')
        temp++;
    //except the line to be deleted
    if (temp == 2 && ch2 == '\n') //making sure to skip a blank line if delete_line=1
        ch2 = getc(id);
​
    if (temp != delete_line)
        putc(ch2, rep);
​
    ch2 = getc(id);
}

fclose(id);
fclose(rep);

remove("id.txt");
rename("rep.txt","id.txt");

data in id.txt

asd123
xcv1323
rijr123
eieir2334

data in lname.txt

Bipul Das
Star Lord
Tony Stark
Vin Diesel
2

There are 2 answers

0
Andreas Wenzel On

The line

ch1 = getc(lname);

truncates the return value of getc from int to char. Therefore, the while loop condition

while (ch1 != EOF)

will always be true, because EOF cannot be represented in a char.

To fix this, you must declare ch1 to have the type int instead of char.

0
user3629249 On

regarding: Whats wrong with this code is its not working after the first file ,i.e., the second file it is niether deleted nor a new file is created with the skipped line of file. what is the issue? Does it has to do something with the rename remove function?

the original file: rep.txt is actually being deleted.

However, this call:

rep = fopen("rep.txt", "w+");

creates an empty file of the same name.