Đây là chương trình C gộp nội dung hai file vào file thứ ba.
Ví dụ:
Đầu vào
java.txt có nội dung "Java is a programing language." kotlin.txt có nội dung " kotlin is a programing language." ttpoint.txt ban đầu rỗng
Đầu ra
files are merged ttpoint.txt sẽ có nội dung cuối "Java is a programing language. kotlin is a programing language."
Thuật toán
Bắt đầu
Khai báo mảng a[] ký tự. Khởi tạo a[] = "Java is a programing language.".
Khai báo i integer. Khởi tạo i =0.
Khai báo f1 con trỏ FILE. Mở "java.txt" ghi dùng f1.
while (a[i] != '\0') fputc(a[i], f1), i++.
Đóng f1.
Khai báo mảng b[] ký tự. Khởi tạo b[] = " kotlin is a programing language.".
Khai báo j integer. Khởi tạo j =0.
Khai báo f2 con trỏ FILE. Mở "kotlin.txt" ghi dùng f2.
while (b[j] != '\0') fputc(b[j], f2), j++.
Đóng f2.
Mở "java.txt" đọc dùng f1.
Mở "ttpoint.txt" ghi dùng f2.
Khai báo f3 con trỏ FILE. Mở "ttpoint.txt" ghi dùng f3.
Khai báo biến c ký tự.
if (f1 == NULL || f2 == NULL || f3 == NULL) thì
In "không thể mở file." Thoát.
While ((c = fgetc(f1)) != EOF) fputc(c, f3).
while ((c = fgetc(f2)) != EOF) fputc(c, f3).
fclose(f3).
Mở ttpoint.txt dùng f3.
In "Merged java.txt and python.txt into ttpoint.txt".
while (!feof(f3)) putchar(fgetc(f3)).
Đóng f1, f2, f3.
Kết thúc.
Ví dụ
#include <stdio.h>
#include <stdlib.h>
int main() {
char a[] = "Java is a programing language.";
int i=0;
FILE *f1;
f1 = fopen("java.txt", "w");
while (a[i] != '\0') {
fputc(a[i], f1);
i++;
}
fclose(f1);
char b[] = "kotlin is a programing language.";
int j =0;
FILE *f2;
f2 = fopen("kotlin.txt", "w");
while (b[j] != '\0') {
fputc(b[j], f2);
j++;
}
fclose(f2);
f1 = fopen("java.txt", "r");
f2 = fopen("kotlin.txt", "r");
FILE *f3 = fopen("ttpoint.txt", "w");
char c;
if (f1 == NULL || f2 == NULL || f3 == NULL) {
puts("Could not open files");
exit(0);
}
while ((c = fgetc(f1)) != EOF)
fputc(c, f3);
while ((c = fgetc(f2)) != EOF)
fputc(c, f3);
fclose(f3);
f3 = fopen("ttpoint.txt", "r");
printf("Merged java.txt and kotlin.txt into ttpoint.txt\n");
while (!feof(f3))
putchar(fgetc(f3));
fclose(f1);
fclose(f2);
fclose(f3);
return 0;
}
Kết quả
Merged java.txt and kotlin.txt into ttpoint.txt Java is a programing language.kotlin is a programing language.