C语言的文件I / O.

我正面临着下面这个function的问题。 我试图从一个位置获取数据,然后搜索指定的字符串。 之后我打印结果值。 这是第一次工作正常。 如果我使用for循环调用该函数但是我无法打印缓冲区值。

void parse_data(char *fname,int flag) { char str[30]="<Response>"; char buffer[1024],temp[1024],temp1[1024]; int nVal=0; FILE *fp; int s_pos; //string position in the text int c_pos; //char position in the text char *string; char ccnt; //char count long lSize; long pos=0; int c; s_pos = -1; c_pos = 0; fp=fopen(fname,"r"); //fseek(fp, 1, SEEK_SET); string = malloc(strlen(str)+1); if(fp==NULL) { printf("Unable to open the file \n"); exit(0); } while (!feof(fp)) { if (c_pos == 0) { for (ccnt = 1; ccnt <= strlen(str); ccnt++) { if (!feof(fp)) { string[ccnt - 1] = getc(fp); if(nVal==1) { buffer[pos++] = string[ccnt -1]; } } //if }//for }//if if (c_pos != 0) if (!feof(fp)) { for (ccnt = 0; ccnt <= strlen(str) - 2; ccnt++) string[ccnt] = string[ccnt + 1]; string[strlen(str) - 1] = getc(fp); if(nVal==1){ buffer[pos++] = string[strlen(str) - 1]; } } if (strcmp(string, str) == 0) { strcpy(str,"</Response>"); s_pos = c_pos; if(nVal==1){ buffer[pos-strlen(str)]='\0'; break; } nVal=1; } c_pos++; } if(fp!=NULL) fclose(fp); //printf("\n The String position is %d=\n",s_pos); if(flag==0) ParsingString_Inserting_To_DataBase(buffer); else if(flag==1) printf("The Buffer Value is %s \n",buffer); } int main() { int i=0; char fname[30]="/tmp/gcc_trans.html"; for(i=0;i<3;i++) parse_data(fname,1); return 0; } 

我试图了解你的代码而失败了。 一些评论:

1.使用有意义的变量名称。 尝试pattern而不是str 。 为ccntnVal使用更好的名称

  1. 而不是复杂的循环,尝试这种方法:

    • 逐个字符阅读,直到找到&
    • 读取N个字节并检查它们是否为lt;Response> 其中N是字符串的长度。 如果是,打破循环。 如果不是,请向后搜索N个字节。

    • 将当前偏移量保存在文件中

    • 使用</Response>重复上面的代码 。 将此代码移动到辅助函数中。

    • N =当前偏移 – 第一个偏移

    • 使用N个字节分配缓冲区
    • 寻求首先抵消
    • 将N个字节读入缓冲区