从c中删除文件中的单词

时间:2017-06-30 11:42:22

标签: c string file

我之前在答案中找到了这段代码,但是当我应用这段代码时,它也会删除第一个单词的第一个字符。每次我应用代码时都会发生这种情况。我不知道问题出在哪里。我想删除一个特定的单词,但不是第一个单词的第一个字符。谁能帮我 ?! P.s抱歉我的英语不好:)

/*
 * C Program Delete a specific Line from a Text File
 */
#include <stdio.h>

int main()
{
    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.c", "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.c", filename);
   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);
     return 0;

}

2 个答案:

答案 0 :(得分:1)

问题是你在编写文件时第一次忽略了一个角色:

fileptr2 = fopen("replica.c", "w");
ch = getc(fileptr1); //<--- This is the problem; you are never writing this one
while (ch != EOF)
{
    ch = getc(fileptr1); //<--- This one is overwriting it

简单的解决方案是将ch = getc(fileptr1);放在while循环的末尾,而不是在开头使用它。

答案 1 :(得分:0)

//open new file in write mode
fileptr2 = fopen("replica.c", "w");
ch = getc(fileptr1);
while (ch != EOF)
{
ch = getc(fileptr1);

在这部分你有问题,你读了第一个字符,而没有在你再次阅读的输出文件中写入。