English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

calloc() and malloc() in C

fseek()

The fseek() in C language is used to move the file pointer to a specific position. The offset and stream are the destination of the pointer, given in the function parameters. If successful, it returns zero, otherwise it returns a non-zero value.

This isfseek()C language syntax

int fseek(FILE *stream, long int offset, int whence)

This is the parameter used infseek(),

  • stream-This is the pointer that identifies the stream.

  • offset-This is the number of bytes from the position.

  • whence-This is the position where the offset is added.

Is specified by one of the following constants.

  • SEEK_END-The end of the file.

  • SEEK_SET-The beginning of the file.

  • SEEK_CUR-The current position of the file pointer.

This isfseek()C language example-

Suppose we have the following content in the "demo.txt" file-

This is demo text!
This is demo text!
This is demo text!
This is demo text!

Now let's look at the code.

Example

#include<stdio.h>
void main() {
   FILE *f;
   f = fopen("demo.txt", "r");
   if(f == NULL) {
      printf("\nCan't open file or file doesn't exist.");
      exit(0);
   }
   fseek(f, 0, SEEK_END);
   printf("The size of the file: %ld bytes", ftell(f));
   getch();
}

Output result

The size of the file: 78 bytes

In the above program, the file "demo.txt" is opened usingfopen();andfseek()The method is used to move the pointer to the end of the file.

f = fopen("demo.txt", "r");
if(f == NULL) {
   printf("\nCan't open file or file doesn't exist.");
   exit(0);
}
fseek(f, 0, SEEK_END);

rewind()

The functionrewind();Used to set the position of the file to the beginning of the given stream. It does not return any value.

This isrewind();C language syntax

void rewind(FILE *stream);

This isrewind();C language example

Suppose we have the following content in the "new.txt" file-

This is demo!
This is demo!

Now, let's look at an example.

Example

#include<stdio.h>
void main() {
   FILE *f;
   f = fopen("new.txt", "r");
   if(f == NULL) {
      printf("\nCan't open file or file doesn't exist.");
      exit(0);
   }
   rewind(f);
   fseek(f, 0, SEEK_END);
   printf("The size of the file: %ld bytes", ftell(f));
   getch();
}

Output result

The size of the file: 28 bytes

In the above program, the file is opened usingfopen();If the pointer variable is null, display that the file cannot be opened or the file does not exist. This functionrewind();Move the pointer to the beginning of the file.

f = fopen("new.txt", "r");
if(f == NULL) {
   printf("\nCan't open file or file doesn't exist.");
   exit(0);
}
rewind(f);