File handling functions

So far, you have come to know about fopen(), fclose(), fprintf(), fscanf(). Let’s talk about some other functions

fputc() and fgetc()

Given a string “Hello world”, fputc() is used to put one-by-one character of this string until it reaches to the null character ‘\0’ at the end of the string.

fgetc() does the job in reverse. It retrieves character by character from a file until it reaches to the end of the file.

fputs() and fgets()

fputs() writes a string in a file 

fgets(string out, size n, FILE* ptr) reads n-1 characters from a file at a time and stores it in the out string.

What’s the difference between fputs() and fprintf()?

You can print formatted output using frpintf() like this

fprintf(ptr, “Hello, %s! You have %d new messages.\n”, “Alice”, 5);

While fputs() can only print plain string

fputs(“Hello, World!”, ptr);

ftell()

This is really an interesting function. This tell you the current position of the file pointer. Let’s take a look

fseek()

What will you do if you are asked to print the 3rd character from the end of a file? Will you go on checking one by one character from the beginning whether it is the 3rd last character? Obviously you can but it will waste your time. Let’s look at a more faster approach:

feek(FILE* ptr, int offset, int origin)

The fseek() built-in function can move the file pointer anywhere you want. It takes 3 parameters:

  1. ptr: The file pointer you want to move
  2. offset: how much you want to move. For example: +3 means 3 character right from current location. -3 means character left from current location.
  3. origin: It can be one of the following
    1. SEEK_SET: set the ptr at the beginning.
    2. SEEK_CUR: set the ptr at current position.
    3. SEEK_END: set the ptr at the end.

For example, we have a file where the contents are

Hello world

Hello from ZERONEINCORE

The underlined characters we are going to find using fseek(). Let’s take a look at the code

NB: After fgetc() is executed at line 7, the ptr is pointing to the next character (R) at line 8. That’s why file pointer is needed to point 3 characters left to print N.

rewind()

rewind(FILE *ptr) is used to point file pointer at the beginning of the file. In other words,

rewind(ptr) is equivalent to fseek(ptr, 0, SEEK_SET)

 

Little fun fact. Do you want to have a keyboard for programming? The ROYAL KLUDGE RK61 is a budget-friendly, compact, wireless keyboard ideal for coding, with hot-swappable switches and Bluetooth connectivity for up to three devices, though it lacks a function row and arrow keys, and has a shorter battery life of around 10 hours.

Thank you