开发者

File read write problem

开发者 https://www.devze.com 2023-02-23 16:58 出处:网络
I wrote the following code.I should changetags with bill but my code does nothing.What can be the problem?My code is this:

I wrote the following code.I should change tags with bill but my code does nothing.What can be the problem?My code is this:

#include <stdio.h>
#inc开发者_StackOverflowlude <string.h>
int main ()
{
  FILE * pFile;

  char tag [6];
  char code[20]="bill";
  pFile = fopen ("example.asm","r+");
  if (pFile==NULL)
  {
    perror("Error");  
  }
  else
  {

  while(!feof(pFile))
  {
    fgets(tag,5,pFile);

    if((tag=="<bp>") && (!feof(pFile)))
    {

        fputs(code,pFile);  

    }

  }

  }
fclose(pFile);
 return 0;
}


You can't compare strings using the == operator since it will compare between two pointers, not the strings they point to, you should use strcmp(tag,"<bp>").


As all people saids in c to comparing strings use strncmp or use pointers.

#include <stdio.h>
#include <string.h>
int main ()
{
  FILE * pFile;

  char tag [6];
  char code[20]="bill";
  pFile = fopen ("example.asm","r+");
  if (pFile==NULL)
  {
    perror("Error");  
  }
  else
  {

  while(!feof(pFile))
  {
    fgets(tag,5,pFile);

    if((strncmp(tag, "<bp>") == 0) && (!feof(pFile)))
    {

        fputs(code,pFile);  

    }

  }

  }
fclose(pFile);
 return 0;
}


For one thing, if (tag == "<bp>") is not right for C. Try strcmp http://www.elook.org/programming/c/strcmp.html


Well at the least you need to change this

tag=="<bp>"

to this

strncmp(tag,"<bp>",4) == 0
0

精彩评论

暂无评论...
验证码 换一张
取 消