← C EnglishChapter 10 of 13

File Input/Output

## Learning Objectives - Work with file pointers - Read and write text files - Read and write binary files - Use file positioning functions ## Opening Files ### fopen ```c #include FILE *fopen(const char *filename, const char *mode); ``` ### File Modes | Mode | Description | Creates | Overwrites | |------|-------------|---------|------------| | `"r"` | Read | No | No | | `"w"` | Write | Yes | Yes | | `"a"` | Append | Yes | No | | `"r+"` | Read/Write | No | No | | `"w+"` | Read/Write | Yes | Yes | | `"a+"` | Read/Append | Yes | No | ### Binary Modes | Mode | Description | |------|-------------| | `"rb"` | Read binary | | `"wb"` | Write binary | | `"ab"` | Append binary | | `"rb+"` | Read/Write binary | ### Example ```c #include int main(void) { FILE *fp = fopen("file.txt", "w"); if (fp == NULL) { perror("Failed to open file"); return 1; } fprintf(fp, "Hello, World!\n"); fclose(fp); return 0; } ``` ## Closing Files ### fclose ```c FILE *fp = fopen("file.txt", "r"); if (fp) { // Use file fclose(fp); } ``` ## Text Output ### fprintf ```c FILE *fp = fopen("output.txt", "w"); fprintf(fp, "Name: %s, Age: %d\n", "Alice", 30); fprintf(fp, "Pi: %.2f\n", 3.14159); fclose(fp); ``` ### fputs ```c FILE *fp = fopen("output.txt", "w"); fputs("Hello\n", fp); fputs("World\n", fp); fclose(fp); ``` ### fputc ```c FILE *fp = fopen("output.txt", "w"); fputc('A', fp); fputc('\n', fp); fclose(fp); ``` ## Text Input ### fscanf ```c FILE *fp = fopen("input.txt", "r"); char name[50]; int age; fscanf(fp, "%s %d", name, &age); printf("%s is %d years old\n", name, age); fclose(fp); ``` ### fgets ```c #include #include FILE *fp = fopen("input.txt", "r"); char line[256]; while (fgets(line, sizeof(line), fp) != NULL) { line[strcspn(line, "\n")] = '\0'; // Remove newline printf("%s\n", line); } fclose(fp); ``` ### fgetc ```c FILE *fp = fopen("input.txt", "r"); int ch; while ((ch = fgetc(fp)) != EOF) { putchar(ch); } fclose(fp); ``` ## Binary I/O ### fwrite ```c #include int data[] = {1, 2, 3, 4, 5}; FILE *fp = fopen("data.bin", "wb"); fwrite(data, sizeof(int), 5, fp); fclose(fp); ``` ### fread ```c #include int data[5]; FILE *fp = fopen("data.bin", "rb"); size_t num = fread(data, sizeof(int), 5, fp); printf("Read %zu integers\n", num); fclose(fp); ``` ## Checking for Errors ### ferror ```c FILE *fp = fopen("file.txt", "r"); if (ferror(fp)) { perror("File error"); } fclose(fp); ``` ### feof ```c FILE *fp = fopen("file.txt", "r"); int ch; while ((ch = fgetc(fp)) != EOF) { putchar(ch); } if (feof(fp)) { printf("\nEnd of file reached\n"); } fclose(fp); ``` ### fread/fwrite Return Value ```c size_t n = fread(buffer, 1, 100, fp); if (n < 100 && ferror(fp)) { perror("Read error"); } ``` ## File Positioning ### ftell ```c FILE *fp = fopen("file.txt", "r"); fseek(fp, 0, SEEK_END); long size = ftell(fp); printf("File size: %ld bytes\n", size); fclose(fp); ``` ### fseek ```c int fseek(FILE *stream, long offset, int whence); // whence: SEEK_SET, SEEK_CUR, SEEK_END fseek(fp, 10, SEEK_SET); // Position at byte 10 fseek(fp, 5, SEEK_CUR); // Move 5 bytes forward fseek(fp, -10, SEEK_END); // 10 bytes before end ``` ### rewind ```c FILE *fp = fopen("file.txt", "r"); // ... read some data ... rewind(fp); // Go back to beginning fclose(fp); ``` ## Temporary Files ### tmpfile ```c FILE *tmp = tmpfile(); // Opens in "w+b" mode fprintf(tmp, "Temporary data\n"); rewind(tmp); char buffer[100]; fgets(buffer, sizeof(buffer), tmp); fclose(tmp); // Automatically deleted when closed ``` ### tmpnam (Avoid) ```c char filename[L_tmpnam]; tmpnam(filename); // Generates unique filename // Use tmpfile() instead - safer ``` ## File Examples ### Copy File (Text) ```c #include int main(int argc, char *argv[]) { if (argc != 3) { fprintf(stderr, "Usage: %s \n", argv[0]); return 1; } FILE *src = fopen(argv[1], "r"); if (src == NULL) { perror("Cannot open source"); return 1; } FILE *dest = fopen(argv[2], "w"); if (dest == NULL) { perror("Cannot open destination"); fclose(src); return 1; } int ch; while ((ch = fgetc(src)) != EOF) { fputc(ch, dest); } fclose(src); fclose(dest); return 0; } ``` ### Count Lines ```c #include int main(int argc, char *argv[]) { if (argc != 2) { fprintf(stderr, "Usage: %s \n", argv[0]); return 1; } FILE *fp = fopen(argv[1], "r"); if (fp == NULL) { perror("Cannot open file"); return 1; } int lines = 0; int ch; while ((ch = fgetc(fp)) != EOF) { if (ch == '\n') { lines++; } } printf("%d lines\n", lines); fclose(fp); return 0; } ``` ### Read CSV ```c #include int main(void) { FILE *fp = fopen("data.csv", "r"); char line[256]; while (fgets(line, sizeof(line), fp) != NULL) { char name[50]; int age; float salary; // Parse: name,age,salary line[strcspn(line, "\n")] = '\0'; sscanf(line, "%49[^,],%d,%f", name, &age, &salary); printf("%s: %d, $%.2f\n", name, age, salary); } fclose(fp); return 0; } ``` ## Standard Input/Output ```c #include // printf to stdout printf("Hello\n"); // scanf from stdin int x; scanf("%d", &x); // fprintf to file fprintf(fp, "Value: %d\n", x); // fscanf from file fscanf(fp, "%d", &x); ``` ## Summary - `fopen()` opens a file, returns FILE pointer - `fclose()` closes an open file - Text: `fprintf()`, `fscanf()`, `fgets()`, `fputs()` - Binary: `fread()`, `fwrite()` - `fseek()` positions within file - `ftell()` returns current position - `feof()` checks end-of-file - `ferror()` checks for errors - Always check return values for errors

Comments

Comments powered by Giscus

To enable comments, add your Giscus embed code here.

Learn more about Giscus →