C File Handling

Learn to read from and write to files, manage file operations in C programs.

Introduction to File Handling

File handling in C allows you to read from and write to files on disk.

Key concepts:
- Files are streams of data
- C provides standard library functions for file operations
- Files must be opened before use and closed after use
- File operations can fail, so error checking is important

Basic file operations:
1. Open a file
2. Read from or write to the file
3. Close the file

File modes:
- "r" - Read mode
- "w" - Write mode (creates new file or overwrites existing)
- "a" - Append mode
- "r+" - Read and write mode
- "w+" - Write and read mode (creates new file)
- "a+" - Append and read mode
```

Opening and Closing Files

Opening Files:
```c
FILE *file_pointer;
file_pointer = fopen("filename.txt", "mode");
```

Closing Files:
```c
fclose(file_pointer);
```

Error checking:
```c
FILE *fp = fopen("data.txt", "r");
if (fp == NULL) {
    printf("Error opening file!\n");
    return 1;
}
// Use the file
fclose(fp);
```

Important points:
- Always check if file opening was successful
- Always close files when done
- fopen() returns NULL on failure
- fclose() returns 0 on success, EOF on failure
```

Reading from Files

Common file reading functions:

1. fgetc() - Read a single character:
```c
int ch = fgetc(fp);
if (ch != EOF) {
    printf("Character: %c\n", ch);
}
```

2. fgets() - Read a line:
```c
char buffer[100];
if (fgets(buffer, sizeof(buffer), fp) != NULL) {
    printf("Line: %s", buffer);
}
```

3. fscanf() - Read formatted data:
```c
int num;
fscanf(fp, "%d", &num);
```

4. fread() - Read binary data:
```c
int data[10];
fread(data, sizeof(int), 10, fp);
```

Writing to Files

Common file writing functions:

1. fputc() - Write a single character:
```c
fputc('A', fp);
```

2. fputs() - Write a string:
```c
fputs("Hello, World!\n", fp);
```

3. fprintf() - Write formatted data:
```c
int age = 25;
fprintf(fp, "Age: %d\n", age);
```

4. fwrite() - Write binary data:
```c
int data[] = {1, 2, 3, 4, 5};
fwrite(data, sizeof(int), 5, fp);
```

File Position and Error Handling

File Position Functions:
```c
// Get current position
long position = ftell(fp);

// Set position to beginning
rewind(fp);

// Set position to specific location
fseek(fp, 10, SEEK_SET);  // From beginning
fseek(fp, -5, SEEK_CUR);  // From current position
fseek(fp, 0, SEEK_END);   // From end
```

Error Handling:
```c
// Check for end of file
if (feof(fp)) {
    printf("End of file reached\n");
}

// Check for errors
if (ferror(fp)) {
    printf("Error occurred while reading file\n");
}

// Clear error flags
clearerr(fp);
```

Practice Examples

Try these examples in our online C compiler to reinforce your learning:

Writing to a File

Demonstrates how to write data to a file using fprintf().

#include <stdio.h>

int main() {
    FILE *fp;
    
    // Open file for writing
    fp = fopen("output.txt", "w");
    if (fp == NULL) {
        printf("Error opening file!\n");
        return 1;
    }
    
    // Write data to file
    fprintf(fp, "Hello, World!\n");
    fprintf(fp, "This is a test file.\n");
    fprintf(fp, "Numbers: %d, %d, %d\n", 10, 20, 30);
    
    // Close file
    fclose(fp);
    printf("Data written to file successfully!\n");
    
    return 0;
}

Reading from a File

Shows how to read data from a file line by line.

#include <stdio.h>

int main() {
    FILE *fp;
    char buffer[100];
    
    // Open file for reading
    fp = fopen("input.txt", "r");
    if (fp == NULL) {
        printf("Error opening file!\n");
        return 1;
    }
    
    // Read and display file contents
    printf("File contents:\n");
    while (fgets(buffer, sizeof(buffer), fp) != NULL) {
        printf("%s", buffer);
    }
    
    // Close file
    fclose(fp);
    
    return 0;
}

Copy File Contents

Demonstrates file copying by reading and writing character by character.

#include <stdio.h>

int main() {
    FILE *source, *destination;
    int ch;
    
    // Open source file
    source = fopen("source.txt", "r");
    if (source == NULL) {
        printf("Error opening source file!\n");
        return 1;
    }
    
    // Open destination file
    destination = fopen("copy.txt", "w");
    if (destination == NULL) {
        printf("Error creating destination file!\n");
        fclose(source);
        return 1;
    }
    
    // Copy file contents character by character
    while ((ch = fgetc(source)) != EOF) {
        fputc(ch, destination);
    }
    
    // Close files
    fclose(source);
    fclose(destination);
    
    printf("File copied successfully!\n");
    return 0;
}

Congratulations!

You've completed the C programming tutorial series! You now have a solid foundation in C programming.