我对C很陌生。我正试图编写一段在I/O流中查找字符串的代码,但我不明白我做错了什么。我知道错误可能在while循环中(在下面的代码中)。我希望函数从流的开头返回以字节为单位的位置,如果由于某种原因失败,则返回-1。它只是不断地为我尝试的任何文件返回-1。
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;}
非常感谢您的任何帮助
如果您简单地对整个文件进行内存映射并在其上运行标准字符串搜索算法,这将更容易
有关内存映射,请参阅:Linux-内存映射文件
有关字符串搜索代码,请参阅:strstr()以获取非空终止的字符串
请检查已更新的注释行
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;}
由于您在look的条件和开头使用了fgetc,因此实际上您将文件的第二个字符与str.update和check的第一个字符进行比较。