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

fseek() vs rewind() in C

Emergency action

EOF represents the end of the file. Ifgetc()If successful, the function will return EOF.

This is an example of EOF in C language,

Assuming we have the file ‘new.txt’ which contains the following.

This is demo!
This is demo!

Now, let’s look at an example.

Example

#include <stdio.h>
int main() {
   FILE *f = fopen("new.txt", "r");
   int c = getc(f);
   while (c != EOF) {
      putchar(c);
      c = getc(f);
   }
   fclose(f);
   getchar();
   return 0;
}

Output result

This is demo!
This is demo!

In the above program, the file is opened usingfopen()When the integer variable c is not equal to EOF, it will read the file.

FILE *f = fopen("new.txt", "r");
int c = getc(f);
while (c != EOF) {
   putchar(c);
   c = getc(f);
}

getc()

It reads a single character from the input and returns an integer value. If it fails, it returns EOF.

This isgetc()C language syntax,

int getc(FILE *stream);

This isgetc()C language example,

Assuming we have the following content in the file ‘new.txt’-

This is demo!
This is demo!

Now, let’s look at an example.

Example

#include <stdio.h>
int main() {
   FILE *f = fopen("new.txt", "r");
   int c = getc(f);
   while (c != EOF) {
      putchar(c);
      c = getc(f);
   }
   fclose(f);
   getchar();
   return 0;
}

Output result

This is demo!
This is demo!

In the above program, the file is opened usingfopen()When the integer variable c is not equal to EOF, it will read the file. This functiongetc()is reading characters from the file. The function

FILE *f = fopen("new.txt", "r");
int c = getc(f);
while (c != EOF) {
   putchar(c);
   c = getc(f);
}

feof()

The functionfeof()used to check the end of the file after EOF. It tests the file end indicator. If successful, it returns a non-zero value, otherwise it returns zero.

This isfeof()C language syntax,

int feof(FILE *stream)

This isfeof()C language example,

Assuming we have the following content in the file ‘new.txt’-

This is demo!
This is demo!

Now, let’s look at an example.

Example

#include <stdio.h>
int main() {
   FILE *f = fopen("new.txt", "r");
   int c = getc(f);
   while (c != EOF) {
      putchar(c);
      c = getc(f);
   }
   if (feof(f))
   printf("\n Reached to the end of file.");
   else
   printf("\n Failure.");
   fclose(f);
   getchar();
   return 0;
}

Output result

This is demo!
This is demo!
Reached to the end of file.

In the above program, the file is opened usingfopen()When the integer variable c is not equal to EOF, it will read the file. This functionfeof()Check again if the pointer has reached the end of the file.

FILE *f = fopen("new.txt", "r");
int c = getc(f);
while (c != EOF) {
   putchar(c);
   c = getc(f);
}
if (feof(f))
printf("\n Reached to the end of file.");
else
printf("\n Failure.");