Undefined behavior ;
The fsetpos function is called to set a position that was not returned by a previous
successful call to the fgetpos function on a stream associated with the same file
(7.19.9.3).
Non-Compliant Code Example
#include <stdio.h>
int main(int argc, char *argv[])
{
FILE *info = fopen( "widget.txt", "r");
int a,b,c;
if(info == NULL)
{
perror("Could not open file");
return 0;
}
if(fscanf(info,"%i %i %i", &a, &b, &c)!=3)
{
fprintf(stderr, "Expected but did not find three integers \n");
fclose(info);
return 0;
}
else
{
printf("abc is %i%i%i\n",a,b,c);
}
int j=3;
if(fsetpos(info, &j)!=0)
{
perror("fsetpos failed");
fclose(info);
return 0;
}
if(fscanf(info,"%i %i %i", &a, &b, &c)!=3)
{
fprintf(stderr, "Expected but did not find %i %i %i \n");
}
else
{
printf("abc is %i%i%i \n",a,b,c);
}
fclose(info);
return 0;
}
}
Compliant Solution
int main(int argc, char argv[])
{
FILE \*info = fopen( "widget.txt", "r");
fpos_t pos;
int a,b,c;
if(info == NULL)
{
perror("Could not open file");
return 0;
}
if(fgetpos(info, &pos)\!=0)
{
perror("fgetpos failed");
fclose(info);
return 0;
}
if(fscanf(info,"%i %i %i", &a, &b, &c)\!=3)
{
fprintf(stderr, "Expected but did not find three integers \n");
fclose(info);
return 0;
}
else
{
printf("abc is %i%i%i\n",a,b,c);
}
if(fsetpos(info, &pos)\!=0)
{
perror("fsetpos failed");
fclose(info);
return 0;
}
if(fscanf(info,"%i %i %i", &a, &b, &c)\!=3)
{
fprintf(stderr, "Expected but did not find %i %i %i \n");
}
else
{
printf("abc is %i%i%i \n",a,b,c);
}
fclose(info);
return 0;
}