我试图创建一个打开文本文件并逐个字符读取其内容的函数,当该函数遇到特定字符串的匹配项时,它将清除该字符串所在的行。 (或至少将每个字符替换为空字符)。
这是我所拥有的:
void clear_blocker ()
{
FILE* fp = fopen("debug_output.txt", "r+"); // opens a file to read and update
char handle [] = // the string to compare from
"Critical: Unexpected Crash Event. Application forced to terminate/task killed";
char buff[] = // allocating the buff statically. lazy counting.
"Critical: Unexpected Crash Event. Application forced to terminate/task killed+";
long cur, n=0, iter;
fseek(fp, 0L, SEEK_SET); // secure rewinding
*buff = NULL; // emptying buff content
for( ; cur != EOF; cur=fgetc(fp)) // loop trough the file, obtaining each char
{
n++; // counter
if(strlen(buff) <= strlen(handle)) buff[n] = cur; // copying strings (size-limited)
else { *buff = NULL; n = 0; } // restarts content of buff to obtain next
if(!strcmp(buff, handle)) // if the content matches the string
{
for(iter = ftell(fp)-strlen(handle); iter<ftell(fp); iter++) // iter indicates the start of the string in the file and it increments to the end
{
fseek(fp, iter, SEEK_SET); // using the iter to set the position indicator
fputc(NULL, fp); // ..and put NULL there
}
break; // breaks out the loop
}
}
}
我的代码存在的问题是它说我在那一行上溢出了数组
buff
:if(strlen(buff) <= strlen(handle)) buff[n] = cur;
而且我相信它还有更多的问题。
最佳答案
我写了一些strstr
函数,因为我没有启用它。我希望它与真实的相似并且可以解决。
char* strstrr ( char *str1, char *str2 )
{
int i
char* left = malloc(strlen(str1)+strlen(str2)+1);
for(i=0; i<strlen(str1); i++)
{
strcpy(left, str2);
strcat(left, &str1[i+strlen(str2)]);
if(!strcmp(&str1[i], left)) { return &str1[i]; }
}
free(left);
return NULL;
}
关于c - 危险的脚本会起作用吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25497755/