按编号删除C中的行

时间:2017-05-14 14:08:19

标签: c

我正在使用C语言处理文件。 任务是从文件中删除不同的行。

我创建了 void del(); 函数,它应该从文件中删除不同的行。程序是runnig,但不要删除一行。

请你纠正我的错误吗?

 void del ()
    {
    FILE *fileptr1, *fileptr2;
    char filename[40];
    char ch;
    int delete_line, temp = 1;

    printf("Enter file name: ");
    scanf("%s", filename);
    //open file in read mode
    fileptr1 = fopen(filename, "r");
    ch = getc(fileptr1);
   while (ch != EOF)
    {
        printf("%c", ch);
        ch = getc(fileptr1);
    }
    //rewind
    rewind(fileptr1);
    printf(" \n Enter line number of the line to be deleted:");
    scanf("%d", &delete_line);
    //open new file in write mode
    fileptr2 = fopen("replica.txt", "w");
    ch = getc(fileptr1);
    while (ch != EOF)
    {
        ch = getc(fileptr1);
        if (ch == '\n')
            temp++;
            //except the line to be deleted
            if (temp != delete_line)
            {
                //copy all lines in file replica.c
                putc(ch, fileptr2);
            }
    }
    fclose(fileptr1);
    fclose(fileptr2);
    remove(filename);
    //rename the file replica.c to original name
    rename("replica.txt", filename);
    printf ("Press ENTER to continue");
    _getch ();
    printf("\n The contents of file after being modified are as follows:\n");
    fileptr1 = fopen(filename, "r");
    ch = getc(fileptr1);
    while (ch != EOF)
    {
        printf("%c", ch);
        ch = getc(fileptr1);
    }

    fclose(fileptr1);
    sub();
};

1 个答案:

答案 0 :(得分:3)

char ch;

This is wronggetc和朋友返回 int 。这不是你可以随意摆脱并继续快乐的方式。

ch = getc(fileptr1);
while (ch != EOF)
 {
     ch = getc(fileptr1);

你正在以这种方式丢失文件的第一个字符。在任何介绍性C书中查找基于getc / fgetc / getchar循环的任何示例。

if (ch == '\n')
    temp++;
if (temp != delete_line)
{
    //copy all lines in file replica.c
    putc(ch, fileptr2);
}

如果您尝试删除第一行,请将其替换为空行。使用调试器来验证。在删除行号N时确定要跳过哪个换行符。请考虑要解决此问题。