0

I have a code that searches for the word "Applicat" and replaces the entire line. Now i am trying to make it search and replace two lines intead of just one, but i am having a little problem. Here is an example text file:

Name: 1234

Applicat: ft_link

Date: today

I would like the script to be able to change the text file to:

Name: 5678

Applicat: None

Date: tomorrow

So far my code works but it would duplicate the Applicat line more than once... What am i doing wrong here? Thanks in advance!

Here is my code:

FILE *input = fopen(buffer1, "r");       /* open file to read */
FILE *output = fopen("temp.txt", "w");

char buffer[512];
while (fgets(buffer, sizeof(buffer), input) != NULL)
    {

static const char text_to_find[] = "Applicat:";     /* String to search for */

static const char text_to_replace[] = "Applicat: None\n";   /* Replacement string */


static const char text_to_find2[] = "Name";     /* String to search for */

static const char text_to_replace2[] = "Name: 5678\n";  /* Replacement string */


char *pos = strstr(buffer, text_to_find);
if (pos != NULL)
{
fputs(text_to_replace, output);

}

char *pos2 = strstr(buffer, text_to_find2);
if (pos2 != NULL)
{
fputs(text_to_replace2, output);

}
else
fputs(buffer, output);




    }
4

2 回答 2

1

改变

char *pos = strstr(buffer, text_to_find);
if (pos != NULL)
{
fputs(text_to_replace, output);

}

char *pos2 = strstr(buffer, text_to_find2);
if (pos2 != NULL)
{
fputs(text_to_replace2, output);

}
else
fputs(buffer, output);

对此:

char *pos = strstr(buffer, text_to_find);
if (pos != NULL)
{
fputs(text_to_replace, output);

}

char *pos2 = strstr(buffer, text_to_find2);
if (pos2 != NULL)
{
fputs(text_to_replace2, output);

}

if(pos==NULL && pos2==NULL)
   fputs(buffer, output);

或者如果你更喜欢

char *pos = strstr(buffer, text_to_find);
char *pos2 = strstr(buffer, text_to_find2);

if(pos==NULL && pos2==NULL)
   fputs(buffer, output);

if (pos2 != NULL)
    fputs(text_to_replace2, output);

if (pos != NULL)
    fputs(text_to_replace, output);
于 2013-11-14T00:00:59.200 回答
1

你只是错过了一个else

char *pos = strstr(buffer, text_to_find);
char *pos2 = strstr(buffer, text_to_find2);
if (pos != NULL) {
    fputs(text_to_replace, output);
} else if (pos2 != NULL) {
    fputs(text_to_replace2, output);
} else
    fputs(buffer, output);
于 2013-11-14T00:02:18.550 回答