2014-04-22 27 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的第一个字符。更新和检查。