Saturday, December 3, 2022
HomeSoftware DevelopmentC - File I/O - GeeksforGeeks

C – File I/O – GeeksforGeeks


On this article you’ll study what are recordsdata in C, why they’re wanted, and deal with normal I/O in C with the assistance of various C capabilities like fopen(), fclose(), fprintf(), fscanf(), getc(), putc(), getw(), fseek(), and so on. A file represents a sequence of bytes no matter being a textual content file or a binary file.

A file is used to retailer enormous information. C supplies a number of file administration capabilities like file creation, opening and studying recordsdata, Writing to the file, and shutting a file. The file is used to retailer related information and file dealing with in C is used to govern the information.

Varieties of Information

There are primarily two sorts of recordsdata that may be dealt with utilizing File Dealing with in C:

1. Textual content Information: These are easy textual content recordsdata which can be saved by the (.txt) extension and might be created or modified by any textual content editor. Textual content file shops information within the type of ASCII characters and are used to retailer a stream of characters.

2. Binary Information: It’s saved in binary format as a substitute of ASCII characters. Binary recordsdata are usually used to retailer numeric Data (int, float, double). Right here information is saved in binary type i.e, (0’s and 1’s).

Totally different Operations Which might be carried out on a file is:

  1. Creation of a brand new file (fopen with attributes as “a” or “a+” or “w” or “w+”).
  2. Opening an present file (fopenopen).
  3. Studying from file (fscanf or fgets).
  4. Writing to a file with fprintf or fputs.
  5. Shifting file pointer related to a given file to a selected place. (fseek, rewind).
  6. Closing a file (shut).

For performing operations on the file, a particular pointer referred to as File pointer is used which might be declared as:

FILE file_ptr;

We are able to open the file as

file_ptr = fopen(“fileName.txt”, “w”);

The second parameter i.e, “w” might be modified in accordance with the desk under:

Opening Modes Description
r Searches file. If the file is opened efficiently fopen( ) hundreds it into reminiscence and units up a pointer that factors to the primary character in it. If the file can’t be opened fopen( ) then it returns NULL.
rb  Open for studying in binary mode. If the file doesn’t exist then fopen( ) will return NULL.
w Searches file. Contents are overwritten if the file exists. A brand new file is created if the file doesn’t exist. Returns NULL, if unable to open the file.
wb Open for writing in binary mode. Its contents are overwritten if the file exists, else the file shall be created. 
a Searches file. If the file is opened efficiently fopen( ) hundreds it into reminiscence and units up a pointer that factors to the final character in it. If the file doesn’t exist, a brand new file is created. Returns NULL, if unable to open the file.
ab  Open for append in binary mode. Knowledge is added to the top of the file. A file shall be created if it doesn’t exist.
r+ Searches file. It’s opened efficiently fopen( ) hundreds it into reminiscence and units up a pointer that factors to the primary character in it. Whether it is unable to open the file it Returns NULL.
rb+  Open for each studying and writing in binary mode. fopen( ) returns NULL if the file doesn’t exist.
w+ Searches file. Its contents are overwritten if the file exists. A brand new file is created if the file doesn’t exist. Returns NULL, if unable to open the file.
wb+ Open for each studying and writing in binary mode. Contents are overwritten if the file exists. It is going to be created if the file doesn’t exist.
a+ Searches file. If the file is opened efficiently fopen( ) hundreds it into reminiscence and units up a pointer that factors to the final character in it. If the file doesn’t exist, a brand new file is created. Returns NULL, if unable to open the file.
ab+ Open for each studying and appending in binary mode. A file shall be created if the file doesn’t exist.

If you wish to deal with binary recordsdata then entry modes like “rb”, “wb”, “ab”, “rb+”, r+b”, “wb+”, “w+b”, “ab+”, “a+b” shall be used largely.

Opening or Making a file in C

To carry out the opening and creation of a file in c we will use fopen() perform which comes below stdio.h header file.

Syntax:

p = fopen(“fileopen”, “mode”);

Instance:

p = fopen(“Howdy.txt”, r);

Studying and Writing to a textual content file in C

fprintf() and fscanf() are used to learn and write in a textual content file in C programming. They count on a pointer to the construction FILE since they’re file variations of print() and scanf().

C

#embrace <stdio.h>

#embrace <stdlib.h>

  

int important()

{

  char str[20];

  FILE* ptr;

  

  ptr = fopen("Howdy.txt", "w+");

    

  if (ptr == NULL) 

  {

    printf("Error Occured Whereas writing to a textual content file !");

    exit(1);

  }

  

  printf("Enter String ");

  fgets(str, 80, stdin);

  

  fputs(str, ptr);

  fclose(ptr);

  

  return 0;

}

Output:

Write to a File

 

The above program takes a string from a consumer and shops it in text_file.textual content.After compiling this program a textual content file named temp_text.txt shall be created within the C_Program folder. Contained in the file, we will see the string that we entered.

Beneath is the C program to learn the contents from the file:

C

#embrace <stdio.h>

#embrace <stdlib.h>

  

int important()

{

  char str[80];

  FILE* ptr;

  

  ptr = fopen("Howdy.txt", "r");

  

  if (ptr == NULL) 

  {

    printf("Error Whereas opening file");

          

    

    

    exit(1);

  }

    

  if(fgets(str, 80, ptr) != NULL)

  {

    places(str);

  }

  fclose(ptr);

  

  return 0;

}

Output:

Readfromfile

 

Studying and Writing to a Binary File

fread() is used to learn from a binary file and fwrite() is used to write down to a file on the disk.

1. Writing to a Binary File

fwrite() perform takes 4 arguments deal with of knowledge, dimension of the information which is to be written on the disk, variety of information sorts, and a pointer to the file the place we wish to write.

Syntax:

fwrite(const void *ptr,size_of_elements,number_of_elements, FILE *a_file);

Beneath is the C program to write down to a binary file:

C

#embrace <stdio.h>

#embrace <stdlib.h>

  

struct Num 

{

  int n1, n2;

};

  

int important()

{

  int n;

  struct Num obj;

  FILE* fptr;

  if ((fptr = fopen("temp.bin", "wb")) == NULL) 

  {

    printf("Error! opening file");

          

    

    

    exit(1);

  }

      

  for (n = 1; n < 10; n++) 

  {

    obj.n1 = n;

    obj.n2 = 12 + n;

    fwrite(&obj, sizeof(struct Num), 

           1, fptr);

  }

    

  fclose(fptr);

  return 0;

}

Output: 

Writetobinary file

 

Rationalization:  Within the above program, we’re creating a brand new file with the identify GFG.bin. Construction with the identify Num has been declared with two numbers – n1, n2 and created an object with the identify obj. In for loop, we’re storing values within the file with the assistance of fwrite() perform. The primary parameter takes the deal with of obj and the second takes the dimensions of the outlined construction Num.

As we have now solely inserted one occasion of obj then the third parameter shall be 1. fptr shall be pointing to the file the place information is saved. And finally, we have now closed the file.

2. Studying from a Binary File

fread() perform additionally takes 4 arguments which can be just like fwrite() perform in C Programming.

Syntax:

fwrite(const void *ptr,size_of_elements,number_of_elements, FILE *a_file);

Beneath is the C program to learn from a binary file:

C

#embrace <stdio.h>

#embrace <stdlib.h>

struct Num 

{

    int n1, n2;

};

  

int important()

{

  int n;

  struct Num obj;

  FILE* fptr;

  if ((fptr = fopen("temp.bin", "rb")) == NULL) 

  {

    printf("Error! opening file");

          

    

    

    exit(1);

  }

      

  

  

  for (n = 1; n < 10; ++n) 

  {

    fread(&obj, sizeof(struct Num), 1, fptr);

    printf("n1: %dtn2: %dn", obj.n1, obj.n2);

  }

    

  fclose(fptr);

  return 0;

}

Output:

Read from binary file

 

Rationalization: Within the above program, we have now learn the identical file GFG.bin and are looping by information one after the other. We learn a single Num report of Num dimension from the file pointed by *fptr into the construction Num. We’ll get the identical report that we inserted within the earlier program. 

Shifting File Tips to Particular Positions

fseek() and rewind() are the 2 strategies in C programming that can be utilized to maneuver the file pointer.

1. fseek() in C Programming

fseek() perform is used to set the file pointer to the required offset and write information into the file.

Syntax:

int fseek(FILE *stream, lengthy int offset, int whence);

Right here,

  • whence might be SEEK_SET, SEEK_CUR and SEEK_END.
  • SEEK_END: It denotes finish of the file.
  • SEEK_SET: It denotes beginning of the file.
  • SEEK_CUR: It denotes the file pointer’s present place.

Beneath is the C program to implement fseek():

C

#embrace <stdio.h>

#embrace <stdlib.h>

  

int important()

{

  char str[80];

  FILE* ptr;

  

  ptr = fopen("Howdy.txt", "w+");

  fputs("Welcome to GeeksforGeeks", ptr);

  

  fseek(ptr, 11,  SEEK_SET);

  fputs("Programming  ", ptr);

  fclose(ptr);

    

  ptr = fopen("Howdy.txt", "r+");

  if(fgets(str, 80, ptr) != NULL)

  {

    places(str);

  }

  

  fclose(ptr);

  return 0;

}

Output:

fseek in C

 

2. rewind() in C

rewind() perform units the file pointer to the start of the file. 

Syntax:

void rewind(FILE *stream);

Beneath is the C Program to implement rewind():

C

#embrace <stdio.h>

#embrace <stdlib.h>

  

int important()

{

  char str[200];

  FILE* ptr;

  

  ptr = fopen("Howdy.txt", "w+");

  fputs("Welcome to GeeksforGeeks", ptr);

  

  fclose(ptr);

    

  ptr = fopen("Howdy.txt", "r+");

  if(fgets(str, 200, ptr) != NULL)

  {

    places(str);

  }

  rewind(ptr);

  if(fgets(str, 200, ptr) != NULL)

  {

    places(str);

  

  

  fclose(ptr);

  return 0;

}

Output:

Rewind in c

 

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments