C – File I/O – GeeksforGeeks

[ad_1]

On this article you’ll be taught what are recordsdata in C, why they’re wanted, and tips on how to 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 forth. A file represents a sequence of bytes no matter being a textual content file or a binary file.

A file is used to retailer big information. C gives 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 info.

Forms of Recordsdata

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

1. Textual content Recordsdata: 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 Recordsdata: It’s saved in binary format as an alternative of ASCII characters. Binary recordsdata are usually used to retailer numeric Data (int, float, double). Right here information is saved in binary kind i.e, (0’s and 1’s).

Completely 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. Transferring file pointer related to a given file to a particular place. (fseek, rewind).
  6. Closing a file (shut).

For performing operations on the file, a particular pointer known 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 based on the desk beneath:

Opening Modes Description
r Searches file. If the file is opened efficiently fopen( ) masses 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 will likely be created. 
a Searches file. If the file is opened efficiently fopen( ) masses 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 tip of the file. A file will likely be created if it doesn’t exist.
r+ Searches file. It’s opened efficiently fopen( ) masses 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 will likely be created if the file doesn’t exist.
a+ Searches file. If the file is opened efficiently fopen( ) masses 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 will likely 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” will likely be used largely.

Opening or Making a file in C

To carry out the opening and creation of a file in c we are able to use fopen() operate which comes underneath 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 anticipate a pointer to the construction FILE since they’re file variations of print() and scanf().

C

#embrace <stdio.h>

#embrace <stdlib.h>

  

int principal()

{

  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 person and shops it in text_file.textual content.After compiling this program a textual content file named temp_text.txt will likely be created within the C_Program folder. Contained in the file, we are able to see the string that we entered.

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

C

#embrace <stdio.h>

#embrace <stdlib.h>

  

int principal()

{

  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 put in writing to a file on the disk.

1. Writing to a Binary File

fwrite() operate takes 4 arguments tackle of knowledge, dimension of the info which is to be written on the disk, variety of information varieties, 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);

Under is the C program to put in writing to a binary file:

C

#embrace <stdio.h>

#embrace <stdlib.h>

  

struct Num 

{

  int n1, n2;

};

  

int principal()

{

  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 title GFG.bin. Construction with the title Num has been declared with two numbers – n1, n2 and created an object with the title obj. In for loop, we’re storing values within the file with the assistance of fwrite() operate. The primary parameter takes the tackle of obj and the second takes the dimensions of the outlined construction Num.

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

2. Studying from a Binary File

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

Syntax:

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

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

C

#embrace <stdio.h>

#embrace <stdlib.h>

struct Num 

{

    int n1, n2;

};

  

int principal()

{

  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, now we have learn the identical file GFG.bin and are looping via 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. 

Transferring File Tips that could 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() operate is used to set the file pointer to the desired 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.

Under is the C program to implement fseek():

C

#embrace <stdio.h>

#embrace <stdlib.h>

  

int principal()

{

  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() operate units the file pointer to the start of the file. 

Syntax:

void rewind(FILE *stream);

Under is the C Program to implement rewind():

C

#embrace <stdio.h>

#embrace <stdlib.h>

  

int principal()

{

  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

 

[ad_2]

Leave a Reply