fseek - cppreference.com

##### cppreference.com

##### Search

Create account

##### Namespaces

- Page
- Discussion

##### Variants

##### Views

- View
- Edit
- History

##### Actions

# fseek

From cppreference.com
< c‎ | io

Defined in header `<stdio.h>` |  |
int fseek( FILE *stream, long offset, int origin ); |  |

Sets the file position indicator for the file stream `stream` to the value pointed to by `offset`. This function can be used to set the indicator beyond the actual end of the file, however, negative position values are not accepted.

### [edit] Parameters

stream | - | file stream to modify
offset | - | number of characters to shift the position relative to origin
origin | - | position to which `offset` is added. It can have one of the following values: SEEK_SET, SEEK_CUR, SEEK_END

### [edit] Return value

​0​ upon success, nonzero value otherwise. Associated EOF flag is cleared for the stream and the effect of any ungetc is undone.

### [edit] Notes

For text streams, the only valid values of `offset` are ​0​ (applicable to any `origin`) and a value returned by an earlier call to ftell (only applicable to `SEEK_SET`).

### [edit] Example

fseek with error checking

Run this code

    #include <stdio.h>
    #include <stdlib.h>

    int main(void)
    {
        /* Prepare an array of f-p values. */
        #define SIZE 5
        double A[SIZE] = {1.,2.,3.,4.,5.};
        /* Write array to a file. */
        FILE * fp = fopen("test.bin", "wb");
        fwrite(A,sizeof(double),SIZE,fp);
        fclose (fp);

        /* Read the f-p values into array B. */
        double B[SIZE];
        fp = fopen("test.bin","rb");

        /* Set the file position indicator in front of third f-p value. */
        if (fseek(fp,sizeof(double)*2L,SEEK_SET) != 0)
        {
           if (ferror(fp))
           {
              perror("fseek()");
              fprintf(stderr,"fseek() failed in file %s at line # %d\n", __FILE__,__LINE__-5);
              exit(EXIT_FAILURE);
           }
        }

        int ret_code = fread(B,sizeof(double),1,fp);   /* read one f-p value  */
        printf("%.1f\n", B[0]);                        /* print one f-p value */

        fclose(fp);
        return EXIT_SUCCESS;
    }

Output:

    3.0

### [edit] See also

fsetpos | moves the file position indicator to a specific location in a file (function) [edit]
fgetpos | gets the file position indicator (function) [edit]
ftell | returns the current file position indicator (function) [edit]
rewind | moves the file position indicator to the beginning in a file (function) [edit]
C++ documentation for fseek

Retrieved from "http://en.cppreference.com/mwiki/index.php?title=c/io/fseek&oldid=69914"