在下面的代码中,我正在做以下事情:
- 使用 fp 获取文件,并在该文件中搜索用双引号编写的字符串
- 将剩余文件写入另一个名为“NewData.txt”的文件
- 重复步骤 1 和 2,直到搜索到所有用双引号编写的字符串并将其放入缓冲区数组中。
但我收到此错误,
./my_script: line 9: 27310 Segmentation fault ./a.out
我没有明白我在代码中做错的地方......
char *read_quoted_string(char outbuff[], FILE *fp){
char *buffer[1000];
int ch;
int i;
int counter=0;
int increment=0;
int prev=ftell(fp);
fseek(fp, 0L, SEEK_END);
int lengthOfFile=ftell(fp);
fseek(fp,prev,SEEK_SET);
fprintf(stdout,"%d",lengthOfFile);
while(lengthOfFile>0){
while(EOF!=(ch=fgetc(fp)))
if(ch == '"') break;
for(i=0;EOF!=(ch=fgetc(fp));++i)
{
if(ch == '"') break;
outbuff[i] = ch;
}
outbuff[i]='\0';
///////////////////////////////////////
char filename3[] = "NewData.txt";
FILE *file3 = fopen ( filename3, "w" );
if(file3!=NULL){
while(EOF!=(ch=fgetc(fp)))
fputc(ch,file3);
}
fclose(file3);
buffer[increment]=outbuff;
increment=increment+1;
fp=file3;
prev=ftell(fp);
fseek(fp, 0L, SEEK_END);
lengthOfFile=ftell(fp);
fseek(fp,prev,SEEK_SET);
}
return buffer[increment];
}
最佳答案
如何使用 SEEK_END 转到文件末尾 然后使用循环从该位置读取。 您首先需要将光标再次设置到起始位置,然后循环文件。
关于C:在文件中搜索内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17093786/