FILE I/O OPERATIONS

In C programming, file input and output are performed using functions from the standard input/output library (stdio.h). The key functions for file input/output are fopen, fclose, fprintf, fscanf, fputc, fgetc, fgets, and fputs.

there are a different operation that can carried out on a file

1.these are first creation of anew file.

2.opening and existing file.

3.reading from a file.

4.writting to a file.

5.moveing to a specific location in a file.

 6.closeing a file.

Ex

 

File *fptr

Fptr= fopen(filename , mode);

File is basicly a data type , and we need to create a pointer variable to work with it(fptr).

Parameter

Description

Filename

The name of the actual file you want to open (or create) , like filename .txt.

Mode

A single character , which represent what you want to do with the file (read write of append);

W – write a file

A  - append a new data to a file

R -read from a file

Ex

FILE *ptr;

//create a file

fptr = fopen(“filename.txt”, “w”);

//close the file

fclose(fptr);  

 

 

 

The file is created in the same directory as your other c file.

 

#include<stdio.h>

int main()

{

  FILE *ptr;

  //create a file on your computer (filename.txt)

  fptr = fopen(“filename.txt”, “w”);

If you want to create a file in a specific folder just provide an absolute path.

fptr= fopen(“c:\directory name\filename.txt”, “w”);

 

Write to a file

 

The w mode means find that file is opening for writing . to insert content to it , you can fprintf().

 

#include<stdio.h>

int main()

{

  FILE *ptr;

  fptr=fopen(“filename.txt”, “w”);

  fprintf(fptr, “some text”);

  fclose(fptr);

  return 0;

}  

 

Append content to a file

If you want to add content to a file , deleting the add content , you can use the ‘a’ mode . the ‘a’ mode append content at the end of file.

Ex

#include<stdio.h>

int main()

{

  FILE *ptr;

  fptr =fopen(“filename.txt”, “a”);

  fprintf(fptr ,“GWG”);

  fclose(fptr);

  return 0;

}

C read file

To read from a file you can use the ‘r’ mode.

FILE *fptr;

fptr=fopen(“filename.txt”, “r”);

This will make the filename.txt

#include<stdio.h>

int main()

{

  FILE *fptr;

  fptr =fopen(“filename.txt”, “r”);

  char string[100];

  fgets(string, 100, fptr);

  printf(“%s”, string);

  fclose(fptr);

  return 0;

}