为什么此代码会跳过第一个字符并在文件末尾打印特殊字符

问题描述 投票:0回答:1
ch = getc(lname);
while (ch != EOF)
{
    ch = getc(lname);
    if (ch == '\n')
        temp++;
    //except the line to be deleted
    if (temp != delete_line)
    {
        //copy all lines in file replica.c
        putc(ch, rep);
    }
}

我有一个包含以下数据的文件

Aryan Verma
Vinayak Sharma
Dev Deol
Ameesh Deol

上面的代码通过将行值放在delete_line中,基本上跳过了我想要的数据行。在这里,temp初始化为1。现在的问题是,此代码正在跳过第一个字符,即本例中的“ A”,并将特殊字符“ÿ”放在文件末尾。例如,delete_line = 3

ryan Verma
Vinayak Sharma
Ameesh Deol
ÿ

此外,如果delete_line设置为1,则会跳过文件中的整行,例如:


Vinayak Sharma
Dev Deol
Ameesh Deol
ÿ

即使将delete_line初始化为1,也请告诉我是否有办法从文件的第一行进行写入。

c file-handling filehandle
1个回答
0
投票

您的代码正在跳过第一个字符,因为您已经在调用getc()以读取第一个字母之后再次调用它。除了使用第一个字符来决定是否进入循环外,您没有对第一个字符进行任何操作,也没有在打印它。

您需要将对getc()的第二个调用移至循环主体的底部,而不是位于顶部:

ch = getc(lname);
while (ch != EOF)
{
    // ch = getc(lname); <-- move this...
    if (ch == '\n')
    ... 
    ch = getc(lname); // <-- ... down here instead
}

关于代码输出ÿ,这也是由于您第二次调用getc()的位置错误。

ÿ的数值为0xFF,当将其视为EOF时,该数值与char相同。在不考虑值getc()的情况下,直到下一次循环迭代时,才检查第二次调用ch的返回值。

您的循环应更像这样:

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

或者,可以这样重写:

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

关于额外的换行符,这是因为您正在打印属于“已删除”行的'\n'字符。遇到'\n'字符时,请先递增temp,然后求值if (temp != delete_line)以调用putc()。当temp等于delete_line时,跳过putc(),但是当到达'\n'delete_line字符时,首先递增temp,使if (temp != delete_line)的值为真,所以您将putc() ] '\n'字符。您需要颠倒这个逻辑。

您的最终循环代码应看起来更像这样:

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++;
}
    
© www.soinside.com 2019 - 2024. All rights reserved.