删除一行的 C 代码

标签 c file io

我是一个 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
}

这给了我很多笑脸。

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

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);
}

但这两个代码之间的实际区别是什么?

最佳答案

赋值的优先级低于不等于,所以:

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

导致read_char得到一个01,比较fgetc()的结果> 调用 '\n'

你需要括号:

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

这会将 fgetc() 结果分配给 read_char,然后再与 '\n' 进行比较。

关于删除一行的 C 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39260437/

相关文章:

c# - FileSystemWatcher 中的 FileNotFoundException

C、MS Windows系统创建临时文件

java - Java中如何查找未关闭的I/O资源?

io - 将 Agda 程序输出到控制台

c -++ 与指针的 += 1 相同吗?

c - 函数指针的问题

c - "Segmentation fault"大文件

c - c中的初始化和赋值

c++ - 从文本文件读取矩阵到二维整数数组 C++

c - 如何将 STDIN 保持在 C 终端的底部