C 檔案寫入、讀取
在 Unix/Linux 中,C 可以透過檔案相關的 **System Call** 操作檔案。常用的系統呼叫如下:
| System Call | 功能 |
|---|---|
| `open()` | 開啟或建立檔案,取得檔案描述元(file descriptor) |
| `read()` | 從檔案讀取資料 |
| `write()` | 將資料寫入檔案 |
| `lseek()` | 移動檔案目前的讀寫位置 |
| `close()` | 關閉檔案 |
檔案描述元通常是一個整數:
- `0`:標準輸入
- `1`:標準輸出
- `2`:標準錯誤輸出
- `3` 以上:程式開啟的其他檔案
以下範例會先建立檔案並寫入文字,再重新開啟檔案並讀出內容。
```c
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h> // open(), O_*
#include <unistd.h> // read(), write(), close()
#include <string.h> // strlen()
int main(void)
{
const char *filename = "example.txt";
const char *message = "Hello, system call!\n";
char buffer[100];
/*
* 開啟檔案:
* O_WRONLY:只寫
* O_CREAT :檔案不存在時建立
* O_TRUNC :檔案存在時清空原有內容
*
* 0644:
* 擁有者可讀寫,其他使用者只能讀取
*/
int fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0644);
if (fd == -1) {
perror("open for writing");
return 1;
}
// 將字串寫入檔案
ssize_t written = write(fd, message, strlen(message));
if (written == -1) {
perror("write");
close(fd);
return 1;
}
printf("寫入 %zd bytes\n", written);
// 完成寫入後關閉檔案
close(fd);
/*
* 重新以唯讀方式開啟檔案
*/
fd = open(filename, O_RDONLY);
if (fd == -1) {
perror("open for reading");
return 1;
}
// 從檔案讀取資料
ssize_t bytes_read = read(fd, buffer, sizeof(buffer) - 1);
if (bytes_read == -1) {
perror("read");
close(fd);
return 1;
}
// 加上字串結尾,方便使用 printf("%s")
buffer[bytes_read] = '\0';
printf("讀取到的內容:%s", buffer);
// 關閉檔案
close(fd);
return 0;
}
```
編譯與執行:
```bash
gcc file_syscall.c -o file_syscall
./file_syscall
```
可能的輸出:
```text
寫入 20 bytes
讀取到的內容:Hello, system call!
```
程式執行後會產生 `example.txt`。
要注意的是,`read()` 和 `write()` 的回傳值代表實際讀取或寫入的位元組數,不一定等於要求的長度。因此在正式程式中,若要確保全部資料都寫入,通常需要反覆呼叫 `write()`,直到所有資料完成。這些函式直接和作業系統核心溝通,與 `fopen()`、`fprintf()`、`fread()` 等 C 標準函式庫介面不同;後者通常在內部再使用檔案系統呼叫。
相關學習地圖、教學課程
C 語言,系統程式