#include <fcntl.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <iostream>
int main() {
int fd[2];
if (pipe(fd) == -1) {
perror("pipe");
return EXIT_FAILURE;
}
pid_t pid = fork();
if (pid < 0) {
perror("fork");
return EXIT_FAILURE;
}
if (pid > 0) {
close(fd[0]);
std::cout << "请输入文本(Ctrl+D结束):" << std::endl;
char buf;
while (std::cin.get(buf)) {
if (write(fd[1], &buf, 1) == -1) {
perror("write to pipe");
break;
}
}
close(fd[1]);
wait(nullptr);
} else {
close(fd[1]);
std::ofstream fileLetters("file1.txt");
std::ofstream fileDigits("file2.txt");
std::ofstream fileOthers("file3.txt");
char ch;
while (read(fd[0], &ch, 1) > 0) {
if (std::isalpha(static_cast<unsigned char>(ch))) {
fileLetters << ch;
} else if (std::isdigit(static_cast<unsigned char>(ch))) {
fileDigits << ch;
} else {
fileOthers << ch;
}
}
close(fd[0]);
fileLetters.close();
fileDigits.close();
fileOthers.close();
}
return 0;
}

