Functions commonly used in Sequential file handling C

Last Updated On Sunday 27th Mar 2022

Data is written in a simple text format and can be read and written sequentially.

fopen()

The fopen() function is used for opening a file for reading, writing, and doing other operations.

	FILE *fopen (const char *file_name, const char *mode)
	
  • file_name represents the file that we want to work on.
  • mode states the purpose for which we want to open the file.
  • r: This opens the file in reading mode and sets the file pointer at the first character of the file.
  • w: This opens the file in write mode. If the file exists, it will be overwritten.
  • a: Opens the file in append mode. Newly entered data will be added at the end of the file.
  • r+: This opens the file in reading and writes mode. The file pointer is set to point at the beginning of the file. The file content will not be deleted if it already exists. It will not create a file if it does not already exist.
  • w+: This also opens the file in reading and write mode. The file pointer is set to point at the beginning of the file. The file content will be deleted if it already exists, but it will be created if it does not exist.
  • a+: This opens a file for reading as well as for appending new content.

fclose()

The fclose() function is used for closing the file.

	int fclose(FILE *file_pointer)
	
  • file_pointer represents the file pointer that is pointing at the open file. The function returns a value if the file is successfully closed.

fgets()

The fgets() function is used for reading a string from the specified file.

	char *fgets(char *string, int length, FILE *file_pointer)
	
  • string: This represents the character array to which the data read from the file will be assigned.
  • length: This represents the maximum number of characters that can be read from the file. The length-1 number of characters will be read from the file.
  • file_pointer: This represents the file pointer that is pointing at the file.

fputs()

The fputs() function is used for writing into the file.

	int fputs (const char *string, FILE *file_pointer)
	
  • The string represents the character array containing the data to be written into the file.
  • The file_pointer phrase represents the file pointer that is pointing at the file.