What is the complete workflow and error handling mechanism for file operations in C language?
File Operation Workflow:
-
Opening Files
cFILE *fopen(const char *filename, const char *mode); // Mode options "r" // Read only "w" // Write only (overwrite) "a" // Append "r+" // Read and write "w+" // Read and write (overwrite) "a+" // Read and write (append) // Binary mode "rb", "wb", "ab", "rb+", "wb+", "ab+" FILE *fp = fopen("data.txt", "r"); if (fp == NULL) { perror("Failed to open file"); return 1; } -
Reading Files
c// Character reading int fgetc(FILE *stream); char *fgets(char *str, int n, FILE *stream); // Formatted reading int fscanf(FILE *stream, const char *format, ...); // Block reading size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream); // Example char buffer[256]; while (fgets(buffer, sizeof(buffer), fp) != NULL) { printf("%s", buffer); } -
Writing Files
c// Character writing int fputc(int c, FILE *stream); int fputs(const char *str, FILE *stream); // Formatted writing int fprintf(FILE *stream, const char *format, ...); // Block writing size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream); // Example fprintf(fp, "Name: %s, Age: %d\n", name, age); -
File Positioning
cint fseek(FILE *stream, long offset, int origin); // origin: SEEK_SET, SEEK_CUR, SEEK_END long ftell(FILE *stream); void rewind(FILE *stream); // Example fseek(fp, 0, SEEK_END); // Move to end of file long size = ftell(fp); // Get file size rewind(fp); // Return to beginning -
Closing Files
cint fclose(FILE *stream); fclose(fp);
Error Handling Mechanism:
-
Checking Return Values
cif (ferror(fp)) { perror("Error reading file"); } if (feof(fp)) { printf("End of file reached\n"); } -
Error Code Handling
cerrno = 0; FILE *fp = fopen("nonexistent.txt", "r"); if (fp == NULL) { if (errno == ENOENT) { printf("File does not exist\n"); } else { perror("Error opening file"); } } -
Clearing Error Status
cclearerr(fp); // Clear error and EOF flags
Best Practices:
-
Resource Management
cFILE *fp = fopen("data.txt", "r"); if (!fp) { return -1; } // Use goto for error handling if (process_data(fp) != 0) { goto cleanup; } cleanup: if (fp) fclose(fp); -
Buffer Control
csetvbuf(fp, NULL, _IOFBF, 4096); // Fully buffered setvbuf(fp, NULL, _IOLBF, 4096); // Line buffered setvbuf(fp, NULL, _IONBF, 0); // Unbuffered -
Temporary Files
cFILE *tmpfp = tmpfile(); if (tmpfp) { // Use temporary file fclose(tmpfp); // Automatically deleted }