我對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;}
任何幫助是極大的讚賞
Ouch。我不知道你的具體問題是什麼,但你已經比這要難3倍。考慮重新思考整個事情。 – Duck
爲了教你如何釣魚,而不是爲所有錯誤返回-1,你可以返回不同的值。這至少會告訴你什麼部分的功能失敗(並且也會幫助我們) –
可能重複[C:在文件中搜索字符串](http://stackoverflow.com/questions/2188914/c-尋找文件中的字符串) –