Home > Back-end >  After running writeCFG repeatedly, the fseek burst Segmentation fault error
After running writeCFG repeatedly, the fseek burst Segmentation fault error

Time:09-30

After running writeCFG repeatedly, the fseek burst Segmentation fault error
Reference code, using the vs c for Linux, Linux environment is ubuntu18.0.4
 int writeCFG (const char * filename/* */, in const char * key/* */, in const char * value/* */in) {
Int flen=8192;
The FILE * pf=NULL;
Char ftemp [8192]={0}, fline [1024]={0}, * fp.//file cache array
Long fsize=0;
Int reg=0;
Int the exit=0;
Pf=fopen (filename, "r +");
If (pf==NULL) {
Pf=fopen (filename, "w +");
}
Fseek (pf, 0, SEEK_END)//an error here
Fsize=ftell (pf);
If (fsize & gt; Flen) {
Printf (" file cannot be more than 8 k \ n ");
Reg=1;
Goto the end;
}
Fseek (pf, 0, SEEK_SET);//the file pointer to the first

//read one line, if there is the key is to modify the value to cache array
while (! The feof (pf)) {
The fgets (fline, 1024, pf);
If (STRSTR (fline, key)!=NULL & amp; & The exit==1)
{
Strcpy (fline, "");
}
If (STRSTR (fline, key)!=NULL & amp; & The exit==0) {//whether the key is
The exit=1;
Sprintf (fline="\ n % s % s", key, value);
}
Strcat (ftemp fline);
}
If (the exit!=1) {//if there is no the key value written to the last line
Sprintf (fline="\ n % s % s", key, value);
Strcat (ftemp fline);
}
If (pf!=NULL) {
The fclose (pf);
Pf=fopen (filename, "w");
Fp=(char *) malloc (sizeof (char) * strlen (ftemp) + 1);
Strcpy (fp, ftemp);
//fp [strlen (fp) - 1]='\ n';
The fputs (fp, pf);
If (fp!=NULL) {
Free (fp);
Fp=NULL;
}
The fclose (pf);
}
End:
If (pf!=NULL)
The fclose (pf);
//to create a file named filename
Return reg.
}


Please,,,

CodePudding user response:

 pf=fopen (filename, "r +"); 
If (pf==NULL) {
Pf=fopen (filename, "w +");
}

This place may have a problem, pf file may not open the success ~


 pf=fopen (filename, "r +"); 
If (pf==NULL) {
Pf=fopen (filename, "w +");
if (! Pf)
return -1;
}

To such a try, if you open is not successful, at least, there will be no mistake

CodePudding user response:

The
reference 1/f, confident boy reply:
 pf=fopen (filename, "r +"); 
If (pf==NULL) {
Pf=fopen (filename, "w +");
}

This place may have a problem, pf file may not open the success ~


 pf=fopen (filename, "r +"); 
If (pf==NULL) {
Pf=fopen (filename, "w +");
if (! Pf)
return -1;
}

To such a try, if you open is not successful, at least, there will not be long error

Should have nothing to do with this, the code in the eighth reference error
  • Related