w3resource

C rewind() function

C library function - rewind()

The rewind() function is used to reposition the file pointer associated with stream to the beginning of the file.

Syntax:

void rewind(FILE *stream)

rewind() Parameters:

Name Description Required /Optional
stream Identifies an address for a file descriptor, which is an area of memory associated with an input or output stream. Required

Return value from rewind()

  • This function does not return any value.

A call to the rewind() function is the same as:

(void) fseek(stream, 0L, SEEK_SET)

except that rewind() shall also clear the error indicator.

Example: rewind() function

Following example first opens a file test.txt for input and output. It writes integers to the file, uses rewind() to reposition the file pointer to the beginning of the file, and then reads in the data.

#include <stdio.h>
FILE *stream; 
int p, q, r, s;
int main(void)
{
    p = 100; q = 200;
    /* Input data in the file */
   stream = fopen("test.txt", "w+");
   fprintf(stream, "%d %d\n", p, q);
    /* Now read the data file */
   rewind(stream);
   fscanf(stream, "%d", &r);
   fscanf(stream, "%d", &s);
   printf("Latest values are: %d and %d\n", r, s);
}

Output:

Latest values are: 100 and 200

C Programming Code Editor:

Previous C Programming: C rewind()
Next C Programming: C setbuf()



Follow us on Facebook and Twitter for latest update.

C Programming: Tips of the Day

Reading a string with scanf :

An array "decays" into a pointer to its first element, so scanf("%s", string) is equivalent to scanf("%s", &string[0]). On the other hand, scanf("%s", &string) passes a pointer-to-char[256], but it points to the same place.

Then scanf, when processing the tail of its argument list, will try to pull out a char *. That's the Right Thing when you've passed in string or &string[0], but when you've passed in &string you're depending on something that the language standard doesn't guarantee, namely that the pointers &string and &string[0] -- pointers to objects of different types and sizes that start at the same place -- are represented the same way.

Ref : https://bit.ly/3pdEk6f