Skip to content

Instantly share code, notes, and snippets.

@024x
Last active August 15, 2023 03:29
Show Gist options
  • Select an option

  • Save 024x/b16ce60101aa72f5fd221b3c957edeb5 to your computer and use it in GitHub Desktop.

Select an option

Save 024x/b16ce60101aa72f5fd221b3c957edeb5 to your computer and use it in GitHub Desktop.
File I/O Operations in C - A gist that explains how to perform file input/output operations in C language with examples. - Satyendra

File I/O Operations in C

Introduction to File I/O

File I/O (Input/Output) operations in C involve working with files to perform tasks such as reading data from files and writing data to files. Files are used for long-term storage of data and allow us to store and retrieve information even after the program has terminated.

In C, file I/O is performed using the stdio.h library, which provides functions and utilities for handling file operations. The main file-related operations include opening, reading, writing, and closing files.

Basic File Operations

Opening Files

To open a file, you need to declare a file pointer variable and associate it with the desired file using the fopen() function. The syntax for opening a file is as follows:

FILE *fptr;
fptr = fopen("filename", "mode");
  • fptr is a file pointer variable that will be used to access the file.
  • "filename" is the name of the file you want to open (e.g., "data.txt").
  • "mode" specifies the purpose for which the file is opened, such as reading ("r"), writing ("w"), or appending ("a").

The fopen() function returns a pointer to the file if it is opened successfully, or NULL if an error occurs.

Reading from Files

Once a file is opened for reading, you can use various functions to read data from it. The most commonly used function is fscanf(), which reads formatted data from the file. Here's an example:

FILE *fptr;
fptr = fopen("data.txt", "r");

int number;
fscanf(fptr, "%d", &number);

fclose(fptr);

In this example, the file "data.txt" is opened for reading, and the value of the first integer in the file is read using fscanf() and stored in the variable number. After reading, the file is closed using fclose().

Writing to Files

To write data to a file, you need to open it in write mode ("w"). You can use functions like fprintf() or fputs() to write data to the file. Here's an example:

FILE *fptr;
fptr = fopen("output.txt", "w");

int number = 42;
fprintf(fptr, "The answer is: %d\n", number);

fclose(fptr);

In this example, the file "output.txt" is opened for writing, and the formatted string "The answer is: %d\n" is written to the file using fprintf(). The value of the variable number is substituted in place of %d. Finally, the file is closed using fclose().

Closing Files

After performing file operations, it is important to close the file using the fclose() function. This ensures that any changes made to the file are saved and the system resources associated with the file are released.

fclose(fptr);

The fclose() function takes the file pointer as an argument and returns an integer value. It returns 0 if the file is closed successfully, or EOF (End-of-File) if an error occurs.

Reading Text Files

Reading text from a file involves opening the file for reading and then using appropriate functions to read the contents. One common way is to use fgets() to read lines of text from the file. Here's an example:

FILE *fptr;
fptr = fopen("data.txt", "r");

char buffer[100];
while (fgets(buffer, sizeof(buffer), f

ptr) != NULL) {
    printf("%s", buffer);
}

fclose(fptr);

In this example, the file "data.txt" is opened for reading, and the fgets() function is used to read lines of text from the file. The contents of each line are stored in the character array buffer, and printf() is used to display the lines on the console. The loop continues until fgets() returns NULL, indicating the end of the file. Finally, the file is closed using fclose().

Error Handling and Common Mistakes

When working with file I/O operations, it's important to handle errors that may occur during the process. Errors can happen if a file fails to open, reading or writing operations encounter issues, or if there are problems with file permissions.

To handle errors, you can check the return values of file-related functions. For example, fopen() returns NULL if it fails to open the file. You can use an if statement to check for errors:

FILE *fptr;
fptr = fopen("data.txt", "r");

if (fptr == NULL) {
    printf("Failed to open the file.\n");
    // Handle the error here
} else {
    // Perform file operations
    fclose(fptr);
}

By checking the return values and using conditional statements, you can handle errors appropriately, such as displaying an error message or taking alternative actions.

Common mistakes to watch out for when working with file I/O include:

  • Forgetting to close the file after performing operations. Always remember to use fclose() to close the file.
  • Not checking for errors during file operations. Always check the return values of file-related functions to handle errors effectively.
  • Overwriting existing files unintentionally. Be cautious when opening files in write mode ("w"), as it clears the file contents. Use "a" (append) mode to add content to an existing file.

Practice Exercises

  1. Write a C program that reads a text file called "input.txt" and counts the number of lines in it. Display the line count on the console.

  2. Write a C program that takes input from the user and writes it to a file called "output.txt". The program should keep accepting input until the user enters "quit" to exit.

  3. Modify the previous program to append new input to the existing "output.txt" file instead of overwriting it.

These practice exercises will help reinforce your understanding of file I/O operations in C and provide hands-on experience with different aspects of reading and writing files.

Remember to consult the C documentation and other reliable resources for further information and examples on file I/O operations.

Sources

Here are some sources that cover file I/O operations in C and provide additional examples and explanations:

  1. GeeksforGeeks: File Handling in C
  2. Tutorialspoint: C - File I/O
  3. Programiz: C File I/O
  4. C File I/O (Wikipedia)
  5. File I/O in C (Studytonight)
  6. C File Handling (Cprogramming.com)
  7. C File I/O Functions (IBM Developer)
  8. C programming language documentation (e.g., man fopen command in Unix-like systems)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment