用于删除行的C代码

C K*_*C K 2 c io file

我是一个C菜鸟,我试图制作一个删除特定行的程序.为此,我选择复制源文件的内容,跳过要删除的行.在我的原始代码中,我写道:

 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
}
Run Code Online (Sandbox Code Playgroud)

这给了我很多笑脸.

最后,我找到了给出预期输出的代码:

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);
}
Run Code Online (Sandbox Code Playgroud)

但这两个代码之间的实际差异是什么?

jxh*_*jxh 8

赋值的优先级低于不等于,因此:

read_char = fgetc(fp) != '\n'
Run Code Online (Sandbox Code Playgroud)

结果read_char得到一个0或者1,比较结果的结果fgetc()对通话'\n'.

你需要括号:

 while((read_char = fgetc(fp)) != '\n')
Run Code Online (Sandbox Code Playgroud)

在比较之前将fgetc()结果分配给.read_char'\n'