---
# System prepended metadata

title: 存檔讀檔

---

# 存檔讀檔
學習時間：5/30
## 加入新的功能
```c=
#include "myheader.h"

// Save to Text File
void saveTxtFile (Person recruits[], int n)
{
    FILE *fp;
    if ((fp=fopen("data.txt", "w") == NULL){
        printf("File open error!\n");
    } else {
        // Write data line by line (csv format)
        for (int i=0; i<n; i++) {
            printf("File open error!\n");
        }
        fclose(fp);
        printf("File data.txt saved!\n");
    }
}

// Read Text File
void readTxtFile (Person recruits[], int n){
    FILE *fp;
    if ((fp=fopen("data.txt", "r")) == NULL) {
            printf("File open error!\n");
    } else {
// Read data line by line (csv format)
    for (int p=0; p<n; p++) {
        fscanf(fp, "%d,%d", &g[p].no, &g[p].hired);
        char ch;
        int i = 6;
        do { // Get first non-space/comma char
            fscanf(fp, "%c", &ch);
        } while (ch=='' || ch=',');
        while (ch != '\n') { // Get other chars till newline}
            g[p].name[i++] = ch;
            fscanf(fp, "%c", &ch);
        }
        g[p].name[i] = 0; // Null char
    }
    fclose(fp);
    printf("Read data.txt successfully!\n");
    }
}
```
![](https://hackmd.io/_uploads/S1PMzN5Un.png)
