从文件中查找子字符串索引的程序
program to find index of a substring from a file
我试图在将文件复制到数组后找到文件中子字符串所在的索引
我怀疑这里面有匹配地址的东西。如果是,还有哪些其他选择?
#include<stdio.h>
#include<string.h>
int main(int argc, char **argv)
{
FILE *fp = fopen(argv[1], "r");
int len, i=0, c=0;
fseek(fp, 0, SEEK_END);
len = ftell(fp); //number of characters in file
rewind(fp);
char ch, arr[len], *p, *q;
while((ch = fgetc(fp)) != EOF ) //copy file into arr[len]
{
arr[i] = ch;
i++;
}
rewind(fp);
char a[200];
while((fgets(a, 200, fp))) //a contains line from fp
{
q=a; //q pointing at base address of a
if((p = strstr(a, arr))!=NULL)
{
while(q!=p)
{
c++;
q++;
}
printf("c >> %d\n", c);
}
}
}
即使文件中存在子字符串,输出也不会打印任何内容,我希望 c 打印数组的索引。
您错过了参数的顺序(除了所有其他问题):
const char * strstr ( const char * str1, const char * str2 );
char * strstr ( char * str1, const char * str2 );
Locate substring
Returns a pointer to the first occurrence of str2 in str1, or a null pointer if str2 is not part of str1.
因此,您永远无法在变量 a
.
中找到文件的全部内容
我试图在将文件复制到数组后找到文件中子字符串所在的索引
我怀疑这里面有匹配地址的东西。如果是,还有哪些其他选择?
#include<stdio.h>
#include<string.h>
int main(int argc, char **argv)
{
FILE *fp = fopen(argv[1], "r");
int len, i=0, c=0;
fseek(fp, 0, SEEK_END);
len = ftell(fp); //number of characters in file
rewind(fp);
char ch, arr[len], *p, *q;
while((ch = fgetc(fp)) != EOF ) //copy file into arr[len]
{
arr[i] = ch;
i++;
}
rewind(fp);
char a[200];
while((fgets(a, 200, fp))) //a contains line from fp
{
q=a; //q pointing at base address of a
if((p = strstr(a, arr))!=NULL)
{
while(q!=p)
{
c++;
q++;
}
printf("c >> %d\n", c);
}
}
}
即使文件中存在子字符串,输出也不会打印任何内容,我希望 c 打印数组的索引。
您错过了参数的顺序(除了所有其他问题):
const char * strstr ( const char * str1, const char * str2 );
char * strstr ( char * str1, const char * str2 );
Locate substring
Returns a pointer to the first occurrence of str2 in str1, or a null pointer if str2 is not part of str1.
因此,您永远无法在变量 a
.