Show List

File Input/Output

In C, you can perform input and output (I/O) operations on files using the standard library functions. This allows you to read data from a file or write data to a file, which can be useful for storing and retrieving information in a more permanent manner.

To perform I/O operations on a file, you first need to open the file using the fopen function. The fopen function takes two arguments: the name of the file and the mode in which to open the file. The mode can be one of the following:

  • "r" - Open the file for reading. If the file does not exist, the function returns NULL.
  • "w" - Open the file for writing. If the file exists, its contents are truncated to zero length. If the file does not exist, a new file is created.
  • "a" - Open the file for writing. If the file exists, the data is appended to the end of the file. If the file does not exist, a new file is created.
  • "r+" - Open the file for reading and writing. If the file does not exist, the function returns NULL.
  • "w+" - Open the file for reading and writing. If the file exists, its contents are truncated to zero length. If the file does not exist, a new file is created.
  • "a+" - Open the file for reading and writing. If the file exists, the data is appended to the end of the file. If the file does not exist, a new file is created.

Once the file is open, you can perform I/O operations on it using the standard library functions.

Here's an example of how to write data to a file in C:

c
Copy code
#include <stdio.h> int main() { FILE *fp; fp = fopen("example.txt", "w"); if (fp == NULL) { printf("Failed to open the file.\n"); return 1; } fprintf(fp, "Hello, World!\n"); fclose(fp); return 0; }

This will create a file named example.txt in the current directory and write the string "Hello, World!" to it.

Here's an example of how to read data from a file in C:

c
Copy code
#include <stdio.h> int main() { FILE *fp; char buffer[100]; fp = fopen("example.txt", "r"); if (fp == NULL) { printf("Failed to open the file.\n"); return 1; } fgets(buffer, 100, fp); printf("%s", buffer); fclose(fp); return 0; }

This will read the contents of the file example.txt and print it to the console.

Note that when you are done with a file, it's important to close it using the fclose function to ensure that all the data has been written to the file and to free up any resources associated with the file.


    Leave a Comment


  • captcha text