getc / putc等價於 getchar/putchar 但可指定流。EOF 為 int 類型,故接收變量必須聲明為 int。
void read_ch(const char *filename, const char *mode) {
FILE *fp = fopen(filename, mode);
if (!fp) { perror(filename); exit(EXIT_FAILURE); }
int ch;
while ((ch = getc(fp)) != EOF) putc(ch, stdout);
fclose(fp);
}
fgets / fputsfgets(buf, n, fp):讀取至換行符、n-1 字符或 EOF,保留 '\n' 並添加 '\0'。fputs(buf, fp):不自動換行,需手動處理。#define MAXLINE 1024
void read_line(const char *filename, const char *mode) {
FILE *fp = fopen(filename, mode);
if (!fp) { perror(filename); exit(EXIT_FAILURE); }
char line[MAXLINE];
while (fgets(line, MAXLINE, fp)) fputs(line, stdout);
fclose(fp);
}
void cross_ch(const char *f1, const char *f2, const char *mode) {
FILE *fp1 = fopen(f1, mode), *fp2 = fopen(f2, mode);
if (!fp1 || !fp2) { perror("open"); exit(EXIT_FAILURE); }
int c1 = getc(fp1), c2 = getc(fp2);
while (c1 != EOF && c2 != EOF) {
while (c1 != EOF && c1 != '\n') { putc(c1, stdout); c1 = getc(fp1); }
if (c1 != EOF) { putc('\n', stdout); c1 = getc(fp1); }
while (c2 != EOF && c2 != '\n') { putc(c2, stdout); c2 = getc(fp2); }
if (c2 != EOF) { putc('\n', stdout); c2 = getc(fp2); }
}
while (c1 != EOF) { putc(c1, stdout); c1 = getc(fp1); }
while (c2 != EOF) { putc(c2, stdout); c2 = getc(fp2); }
fclose(fp1); fclose(fp2);
}
void cross_line(const char *f1, const char *f2, const char *mode) {
FILE *fp1 = fopen(f1, mode), *fp2 = fopen(f2, mode);
if (!fp1 || !fp2) { perror("open"); exit(EXIT_FAILURE); }
char l1[MAXLINE], l2[MAXLINE];
while (fgets(l1, MAXLINE, fp1) && fgets(l2, MAXLINE, fp2)) {
fputs(l1, stdout); fputs(l2, stdout);
}
while (fgets(l1, MAXLINE, fp1)) fputs(l1, stdout);
while (fgets(l2, MAXLINE, fp2)) fputs(l2, stdout);
fclose(fp1); fclose(fp2);
}
'\n')
static void strip_nl(char *s) {
size_t len = strlen(s);
if (len && s[len-1] == '\n') s[len-1] = '\0';
}
void cat_line(const char *f1, const char *f2, const char *mode) {
FILE *fp1 = fopen(f1, mode), *fp2 = fopen(f2, mode);
if (!fp1 || !fp2) { perror("open"); exit(EXIT_FAILURE); }
char l1[MAXLINE], l2[MAXLINE];
while (fgets(l1, MAXLINE, fp1) && fgets(l2, MAXLINE, fp2)) {
strip_nl(l1);
fputs(l1, stdout); fputs(l2, stdout);
}
while (fgets(l1, MAXLINE, fp1)) fputs(l1, stdout);
while (fgets(l2, MAXLINE, fp2)) fputs(l2, stdout);
fclose(fp1); fclose(fp2);
}
fopen 返回值。fgets/fputs),效率高且易處理文本。MAXLINE 需足夠大以容納最長行,否則行會被截斷。fread/fwrite 配合 "rb"/"wb" 模式。