C – File I/O – GeeksforGeeks

[ad_1]

On this article you’ll be taught what are recordsdata in C, why they’re wanted, and deal with commonplace I/O in C with the assistance of various C features 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 large information. C supplies a number of file administration features 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.

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 are saved by the (.txt) extension and will 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 Info (int, float, double). Right here information is saved in binary kind i.e, (0’s and 1’s).

Completely different Operations Which will 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 referred to as File pointer is used which will 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” will 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 might 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 tip of the file. A file might 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 might 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” might be used principally.

Opening or Making a file in C

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

Syntax:

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

Instance:

p = fopen(“Hey.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

#embody <stdio.h>

#embody <stdlib.h>

  

int important()

{

  char str[20];

  FILE* ptr;

  

  ptr = fopen("Hey.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 might be created within the C_Program folder. Contained in the file, we will see the string that we entered.

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

C

#embody <stdio.h>

#embody <stdlib.h>

  

int important()

{

  char str[80];

  FILE* ptr;

  

  ptr = fopen("Hey.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 handle of information, measurement of the information 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

#embody <stdio.h>

#embody <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() operate. The primary parameter takes the handle 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 might be 1. fptr might be pointing to the file the place information is saved. And eventually, now we have closed the file.

2. Studying from a Binary File

fread() operate additionally takes 4 arguments which are just 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

#embody <stdio.h>

#embody <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, now we have learn the identical file GFG.bin and are looping by means of data one after the other. We learn a single Num document of Num measurement from the file pointed by *fptr into the construction Num. We’ll get the identical document that we inserted within the earlier program. 

Transferring 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() 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 will 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

#embody <stdio.h>

#embody <stdlib.h>

  

int important()

{

  char str[80];

  FILE* ptr;

  

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

  fputs("Welcome to GeeksforGeeks", ptr);

  

  fseek(ptr, 11,  SEEK_SET);

  fputs("Programming  ", ptr);

  fclose(ptr);

    

  ptr = fopen("Hey.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

#embody <stdio.h>

#embody <stdlib.h>

  

int important()

{

  char str[200];

  FILE* ptr;

  

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

  fputs("Welcome to GeeksforGeeks", ptr);

  

  fclose(ptr);

    

  ptr = fopen("Hey.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