Public App

a blog about technology

File I/O (Input/Output) in C Language

File I/O (Input/Output) in C Language refers to the ability to read from and write to files using C language. The standard I/O library in C provides a set of functions for file I/O operations.

The following are some of the commonly used functions for file I/O in C:

fopen()

This function is used to open a file in a specific mode (read, write, append, etc.). It takes two arguments: the name of the file and the mode in which it is to be opened. The mode can be “r” for read mode, “w” for write mode, “a” for append mode, or “r+” for read and write mode.

FILE *fp;
fp = fopen("file.txt", "r"); // opens the file "file.txt" in read mode

fclose()

This function is used to close a file that has been opened using the fopen() function. It takes one argument: the file pointer that points to the file that is to be closed.

FILE *fp;
fp = fopen("file.txt", "r");
fclose(fp); // closes the file "file.txt"

fprintf()

This function is used to write formatted output to a file. It takes two arguments: the file pointer that points to the file to which the output is to be written and the format string that specifies the format of the output.

FILE *fp;
fp = fopen("file.txt", "w");
fprintf(fp, "Hello, world!"); // writes the string "Hello, world!" to the file "file.txt"
fclose(fp);

fscanf()

This function is used to read formatted input from a file. It takes two arguments: the file pointer that points to the file from which the input is to be read and the format string that specifies the format of the input.

FILE *fp;
int x;
fp = fopen("file.txt", "r");
fscanf(fp, "%d", &x); // reads an integer from the file "file.txt" and stores it in the variable x
fclose(fp);

fgetc() and fputc()

These functions are used to read and write a single character from and to a file, respectively. The fgetc() function takes one argument: the file pointer that points to the file from which the character is to be read. The fputc() function takes two arguments: the character that is to be written to the file, and the file pointer that points to the file to which the character is to be written.

FILE *fp;
char c;
fp = fopen("file.txt", "r");
c = fgetc(fp); // reads a single character from the file "file.txt" and stores it in the variable c
fclose(fp);

fp = fopen("file.txt", "w");
fputc('A', fp); // writes the character 'A' to the file "file.txt"
fclose(fp);

Note that file I/O operations can also be performed using the low-level file I/O functions such as open(), read(), write(), and close(). However, the standard I/O library functions provide a higher-level interface that is easier to use and provides more functionality.

Amitesh Kumar

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top