C Library Function - fsetpos()
Description
C Library Function **int fsetpos(FILE stream, const fpos_t pos) Set the file position of the given stream stream to the given position. The argument pos is the position given by the function fgetpos.
Declaration
Below is the declaration of the fsetpos() function.
int fsetpos(FILE *stream, const fpos_t *pos)
Parameters
- stream -- This is a pointer to a FILE object that identifies the stream.
- pos -- This is a pointer to a fpos_t object that contains the position previously obtained via fgetpos.
Return Value
If successful, the function returns zero; otherwise, it returns a nonzero value and sets the global variable errno to a positive value that can be interpreted by perror.
Example
The following example demonstrates the use of the fsetpos() function.
Example
#include
int
main
(
)
{
FILE
fp
;
fpos_t position
;
fp
=
fopen
(
"file.txt"
,
"w+"
)
;
fgetpos
(
fp
,
&
position
)
;
fputs
(
"Hello, World!"
,
fp
)
;
fsetpos
(
fp
,
&
position
)
;
fputs
(
"This will overwrite the previous content"
,
fp
)
;
fclose
(
fp
)
;
return
(
0
)
;
}
Let us compile and run the program above, which will create a file file.txt, whose content is as follows. First we use the fgetpos() function to get the initial position of the file, then we write to the file Hello, World!, then we use fsetpos() function to reset the write pointer to the beginning of the file and rewrite the file with the following content:
这将覆盖之前的内容
Now let us use the following program to view the content of the file above:
Example
#include
int
main
(
)
{
FILE
fp
;
int
c
;
fp
=
fopen
(
"file.txt"
,
"r"
)
;
while
(
1
)
{
c
=
fgetc
(
fp
)
;
if
(
feof
(
fp
)
)
{
break
;
}
printf
(
"%c"
,
c
)
;
}
fclose
(
fp
)
;
return
(
0
)
;
}
C Standard Library -