#include
#include
#include
int find(FILE* p_file, char* pStr)
{
int iPos = ftell(p_file);
char chBuff = 'a';
int iReadNum = 0;
for(pStr++;
iReadNum = fread(&chBuff, 1, 1, p_file), iReadNum && *pStr;
++pStr)
{
if (*pStr != chBuff)
{
fseek(p_file, iPos, SEEK_SET);
return 0;
}
}
if(!(*pStr))
{
return iPos;
}
if(iReadNum == 0)
{
fseek(p_file, iPos, SEEK_SET);
return 0;
}
}
void fun(char* pString)
{
FILE* p_file = fopen("test.txt", "a+b");
// 文件内容为121212123454574569
if(!p_file)
{
printf("打开文件失败\n");
return ;
}
char buf = 'a';
char char_arr[10];
strcpy(char_arr, pString);
int iPos = 0;
while( fread(&buf, 1, 1, p_file))
{
if(buf == char_arr[0])
{
if( iPos = find(p_file, char_arr))
{
printf("找到%s\t的位置为: %d\n", pString, iPos);
fclose(p_file);
return ;
}
}
}
printf("没有找到%s\n", pString);
fclose(p_file);
}
int main()
{
fun("123");
fun("bcd");
fun("23");
fun("456");
return 0;
}
对于查找字符串的长度假设不会超过10.。这里不考虑越界问题。只看实现方法