Manufaktur industri
Industri Internet of Things | bahan industri | Pemeliharaan dan Perbaikan Peralatan | Pemrograman industri |
home  MfgRobots >> Manufaktur industri >  >> Industrial programming >> Bahasa C

Penanganan File C: Menguasai I/O dengan fopen, fprintf, fread, dan fseek

Penanganan File C

Tutorial ini memandu Anda melalui I/O file dalam C, mencakup operasi standar dan biner dengan contoh yang jelas dan praktis.

A file is a logical container on a computer’s storage that holds data for long‑term use.


Menggunakan File?


Jenis File

In C, you’ll encounter two primary file types:

  1. Text files
  2. Binary files

Text Files

Plain‑text files (e.g., .txt) are editable with any text editor. They’re easy to read, maintain, and transfer but occupy more space and offer minimal security.

Binary Files

Binary files (commonly .bin) store data as raw bytes (0s and 1s). They are compact, not human‑readable, and provide better data integrity and security.


Operasi File Inti

Regardless of type, C file handling revolves around four operations:

  1. Create a new file
  2. Open an existing file
  3. Close a file
  4. Read from or write to a file

Menyiapkan Pointer File

All file operations require a FILE * pointer to reference the open file:

FILE *fptr;

Membuka File: Pembuatan dan Pengeditan

The fopen() function (declared in stdio.h) opens a file and returns a FILE * pointer. Its syntax is:

fptr = fopen("filename", "mode");

Example usage:

fopen("E:\\cprogram\\newprogram.txt", "w"); fopen("E:\\cprogram\\oldprogram.bin", "rb");

Explanation:

Opening Modes in Standard I/O
ModeMeaningBehavior if file is missing
rOpen for readingReturns NULL
rbOpen for binary readingReturns NULL
wOpen for writing (overwrite)Creates file if absent
wbOpen for binary writing (overwrite)Creates file if absent
aOpen for appendingCreates file if absent
abOpen for binary appendingCreates file if absent
r+Read and writeReturns NULL
rb+Read and write in binaryReturns NULL
w+Read and write (overwrite)Creates file if absent
wb+Read and write in binary (overwrite)Creates file if absent
a+Read and appendCreates file if absent
ab+Read and binary appendCreates file if absent

Menutup File

After all I/O operations, always close the file with fclose() to release resources and flush buffers:

fclose(fptr);

Text File I/O

Text files are handled with fprintf() and fscanf(), the file‑based counterparts of printf() and scanf(). They require a FILE * pointer as the first argument.

Contoh 1: Menulis ke File Teks

#include <stdio.h> #include <stdlib.h> int main() { int num; FILE *fptr; // Adjust the path for your OS fptr = fopen("C:\\program.txt", "w"); if (fptr == NULL) { printf("Error opening file\n"); exit(EXIT_FAILURE); } printf("Masukkan angka: "); scanf("%d", &num); fprintf(fptr, "%d", num); fclose(fptr); return 0; }

This program captures an integer from the user and writes it to program.txt.

Contoh 2: Membaca dari File Teks

#include <stdio.h> #include <stdlib.h> int main() { int num; FILE *fptr; fptr = fopen("C:\\program.txt", "r"); if (fptr == NULL) { printf("Error opening file\n"); exit(EXIT_FAILURE); } fscanf(fptr, "%d", &num); printf("Nilai yang dibaca: %d\n", num); fclose(fptr); return 0; }

Running this after the first example will display the stored integer.

Additional utilities such as fgetc() and fputc() follow the same pattern.


Binary File I/O

Binary files are manipulated with fwrite() for writing and fread() for reading. Both functions accept four arguments: pointer to data, size of each element, number of elements, and FILE * pointer.

Writing to a Binary File

fwrite(addressData, sizeData, numberData, filePointer);

Contoh 3: Menulis ke File Biner Menggunakan fwrite()

#include <stdio.h> #include <stdlib.h> struct threeNum { int n1, n2, n3; }; int main() { int i; struct threeNum num; FILE *fptr; fptr = fopen("C:\\program.bin", "wb"); if (fptr == NULL) { printf("Error opening file\n"); exit(EXIT_FAILURE); } for (i = 1; i < 5; ++i) { num.n1 = i; num.n2 = 5 * i; num.n3 = 5 * i + 1; fwrite(&num, sizeof(struct threeNum), 1, fptr); } fclose(fptr); return 0; }

Membaca dari File Biner

The corresponding fread() signature mirrors fwrite():

fread(addressData, sizeData, numberData, filePointer);

Contoh 4: Membaca dari File Biner Menggunakan fread()

#include <stdio.h> #include <stdlib.h> struct threeNum { int n1, n2, n3; }; int main() { int i; struct threeNum num; FILE *fptr; fptr = fopen("C:\\program.bin", "rb"); if (fptr == NULL) { printf("Error opening file\n"); exit(EXIT_FAILURE); } for (i = 1; i < 5; ++i) { fread(&num, sizeof(struct threeNum), 1, fptr); printf("n1: %d\tn2: %d\tn3: %d\n", num.n1, num.n2, num.n3); } fclose(fptr); return 0; }

This program reproduces the data written in Example 3.


Akses Acak dengan fseek()

When a file contains many records, sequentially traversing to a specific entry can be inefficient. fseek() moves the file pointer to an arbitrary position, enabling direct access.

Syntax

fseek(FILE *stream, long int offset, int whence);
Whence values for fseek()
ConstantMeaning
SEEK_SETOffset starts from the file beginning.
SEEK_CUROffset starts from the current cursor position.
SEEK_ENDOffset starts from the file end.

Contoh 5: Pembacaan Terbalik dengan fseek()

#include <stdio.h> #include <stdlib.h> struct threeNum { int n1, n2, n3; }; int main() { int i; struct threeNum num; FILE *fptr; fptr = fopen("C:\\program.bin", "rb"); if (fptr == NULL) { printf("Error opening file\n"); exit(EXIT_FAILURE); } // Move to the last record fseek(fptr, -sizeof(struct threeNum), SEEK_END); for (i = 1; i < 5; ++i) { fread(&num, sizeof(struct threeNum), 1, fptr); printf("n1: %d\tn2: %d\tn3: %d\n", num.n1, num.n2, num.n3); // Step back two records (current + one more) to read the previous entry fseek(fptr, -2 * sizeof(struct threeNum), SEEK_CUR); } fclose(fptr); return 0; }

This snippet demonstrates how to traverse a binary file in reverse, starting from the last record.


Bahasa C

  1. Pengoperasian File Java dengan java.io – Pembuatan, Pembacaan, Penulisan & Penghapusan
  2. Memahami Berkas STL: Tulang Punggung Pencetakan 3D
  3. Menguasai File I/O dalam Verilog: Buka, Baca, Tulis, dan Tutup
  4. Menguasai File I/O dalam C: Membuat, Membuka, dan Mengelola File
  5. Memahami File Header C: Tipe, Penggunaan, dan Praktik Terbaik
  6. Menguasai Penanganan Kesalahan dalam C: Praktik Terbaik & Teknik
  7. Menguasai Input/Output File C++: Membaca dan Menulis dengan fstream
  8. Menguasai Penanganan Sinyal C++: Pengelolaan Interupsi Aman dan Penutupan Program yang Bersih
  9. Menguasai Penanganan Pengecualian C#: Strategi & Praktik Terbaik
  10. Menguasai File I/O C#: Membaca, Menulis, dan Mengelola Aliran