我对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;}
非常感谢任何帮助
答案 0 :(得分:0)
如果您只是对整个文件进行内存映射并在其上运行标准的字符串搜索算法,这将会容易得多。
有关内存映射,请参阅:Linux - Memory Mapped File
有关字符串搜索代码,请参阅:strstr() for a string that is NOT null-terminated
答案 1 :(得分:0)
请检查更新评论的行
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;}
因为您在条件和开始时使用fgetc,所以实际上将文件的第二个char与str的第一个char进行比较。更新并检查。