乐闻世界logo
搜索文章和话题

What is the complete workflow and error handling mechanism for file operations in C language?

2月18日 17:15

What is the complete workflow and error handling mechanism for file operations in C language?

File Operation Workflow:

  1. Opening Files

    c
    FILE *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; }
  2. 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); }
  3. 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);
  4. File Positioning

    c
    int 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
  5. Closing Files

    c
    int fclose(FILE *stream); fclose(fp);

Error Handling Mechanism:

  1. Checking Return Values

    c
    if (ferror(fp)) { perror("Error reading file"); } if (feof(fp)) { printf("End of file reached\n"); }
  2. Error Code Handling

    c
    errno = 0; FILE *fp = fopen("nonexistent.txt", "r"); if (fp == NULL) { if (errno == ENOENT) { printf("File does not exist\n"); } else { perror("Error opening file"); } }
  3. Clearing Error Status

    c
    clearerr(fp); // Clear error and EOF flags

Best Practices:

  1. Resource Management

    c
    FILE *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);
  2. Buffer Control

    c
    setvbuf(fp, NULL, _IOFBF, 4096); // Fully buffered setvbuf(fp, NULL, _IOLBF, 4096); // Line buffered setvbuf(fp, NULL, _IONBF, 0); // Unbuffered
  3. Temporary Files

    c
    FILE *tmpfp = tmpfile(); if (tmpfp) { // Use temporary file fclose(tmpfp); // Automatically deleted }
标签:C语言