文件读写问题
我写了下面的代码。我应该用bill更改标签,但我的代码什么都不做。可能是什么问题?我的代码是这样的:
#include #include 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=="") && (!feof(pFile))) { fputs(code,pFile); } } } fclose(pFile); return 0; }
您无法使用==
运算符比较字符串,因为它将在两个指针之间进行比较,而不是它们指向的字符串,您应该使用strcmp(tag,"
。
正如所有人都在c中比较字符串使用strncmp
或使用pointers
。
#include #include 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, "") == 0) && (!feof(pFile))) { fputs(code,pFile); } } } fclose(pFile); return 0; }
首先, if (tag == "
不适合C.尝试strcmp
http://www.elook.org/programming/c/strcmp.html
至少你需要改变它
tag==""
对此
strncmp(tag,"",4) == 0