Çetin Köktürk Çetin Köktürk - 3 months ago 20
C Question

C Code for Deleting a Line

I am a C noob, and I was trying to make a program to delete a specific line. For this, I chose to copy the contents of the source file, skipping the line intended for deletion. In my original code, I wrote:

while(read_char = fgetc(fp) != '\n') //code to move the cursor position to end of line
{
printf("%c",read_char); //temporary code to see the skipped characters
}


which gave me lots of smileys.

In the end I found the code which gave the intended output:

read_char=fgetc(fp);
while(read_char != '\n') //code to move the cursor position to end of line
{
printf("%c",read_char); //temporary code to see the skipped characters
read_char=fgetc(fp);
}


But what is the actual difference between these two codes?

jxh jxh
Answer

Assignment has lower priority than not-equal, so:

read_char = fgetc(fp) != '\n'

results in read_char getting a 0 or 1, the result of comparing the result of the fgetc() call against '\n'.

You need parentheses:

 while((read_char = fgetc(fp)) != '\n')

which will assign the fgetc() result to read_char before comparing with '\n'.