2011-04-10 45 views
0

我寫了下面code.I應該改變標籤與法案,但我的代碼並nothing.What可問題我的代碼是這樣的:?文件讀寫問題

#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((tag=="<bp>") && (!feof(pFile))) 
    { 

     fputs(code,pFile); 

    } 

    } 

    } 
fclose(pFile); 
return 0; 
} 

回答

0

那麼你需要這個

tag=="<bp>" 

改變這個

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

它編譯完美,因爲'tag'和'「」'都是同一類型,'字符*'的三分球,他也因此被比較的地址,而不是字符串。 – 2011-04-10 10:57:20

+0

@Blag - 對。我大約10年沒有運行c編譯器,我有點生疏。 – Hogan 2011-04-10 10:59:58

+0

非常感謝。它的工作原理。 – Cem 2011-04-10 11:01:50

3

使用==操作,因爲它將兩個指針,而不是它們指向的字符串之間的比較不能比較字符串,你應該使用strcmp(tag,"<bp>")

1

正如所有人都說c在比較字符串時使用strncmp或使用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; 
}