2014-04-22 70 views
0

我對C非常陌生。我試圖編寫一個在I/O流中查找字符串的代碼,但我不明白我做錯了什麼。我知道這個錯誤可能是在大的while循環中(在下面的代碼中)。 我希望函數以字節的形式從流的開頭返回位置,如果由於某種原因失敗,則返回-1。它只是保持返回-1爲我嘗試它的任何文件。查找在I/O流-C中重新定位字符串?

long find_string(const char *str, const char *filename, long offset) 
{ 
FILE *f = fopen(filename, "r"); 
if (!f){ 
    return -1; 
} 

int s=0,c; 

c = fgetc(f); 
if(c == EOF){ 
    return -1; 
} 

char *check = malloc(sizeof(char)); 

fseek(f, 0L, SEEK_END); // Sees and stores how long the file is 
long sz = ftell(f); 
fseek(f, 0L, SEEK_SET); 

if(fseek(f, offset,SEEK_SET) != 0){ // finds the position of offset 
    return -1; 
} 


while(fgetc(f) != EOF){ 
    c = fgetc(f); 
    if(c == str[0] && ftell(f) < sz){ 
     check[0] = c; 
     offset = ftell(f); 
     } 

     s++; 
     for (unsigned int r=1; r < (strlen(str));r++){ 
      c = fgetc(f); 
      if(c == str[s]){ 
        check = realloc(check, sizeof(char)*s); 
        check[s] = c; 
        s++; 
      }     
     } 

    if(strcmp(check, str)==0){ 
     free(check); 
     fclose(f); 
     break; 

    } 
    else{ 
     check = realloc(check, sizeof(char)); 
     offset = -1; 
    } 
} 
return offset;} 

任何幫助是極大的讚賞

+0

Ouch。我不知道你的具體問題是什麼,但你已經比這要難3倍。考慮重新思考整個事情。 – Duck

+1

爲了教你如何釣魚,而不是爲所有錯誤返回-1,你可以返回不同的值。這至少會告訴你什麼部分的功能失敗(並且也會幫助我們) –

+0

可能重複[C:在文件中搜索字符串](http://stackoverflow.com/questions/2188914/c-尋找文件中的字符串) –

回答

0

,請查看與評論,因爲你正在使用龜etc在狀態更新

long find_string(const char *str, const char *filename, long offset) 
{ 
FILE *f = fopen(filename, "r"); 
if (!f){ 
    return -1; 
} 

int s=0,c; 

c = fgetc(f); 
if(c == EOF){ 
    return -1; 
} 

char *check = malloc(sizeof(char)); 

fseek(f, 0L, SEEK_END); // Sees and stores how long the file is 
long sz = ftell(f); 
fseek(f, 0L, SEEK_SET); 

if(fseek(f, offset,SEEK_SET) != 0){ // finds the position of offset 
    return -1; 
} 

    c = fgetc(f); // Updated 
while(c != EOF){ // Updated 
    if(c == str[0] && ftell(f) < sz){ 
     check[0] = c; 
     offset = ftell(f); 
     } 

     s++; 
     for (unsigned int r=1; r < (strlen(str));r++){ 
      c = fgetc(f); 
      if(c == str[s]){ 
        check = realloc(check, sizeof(char)*s); 
        check[s] = c; 
        s++; 
      }     
     } 

    if(strcmp(check, str)==0){ 
     free(check); 
     fclose(f); 
     break; 

    } 
    else{ 
     check = realloc(check, sizeof(char)); 
     offset = -1; 
    } 
    c = fgetc(f); //Updated 
} 
return offset;} 

線和開始看,你實際上比較文件的第二個字符與str的第一個字符。更新和檢查。