//
// Created by Lin on 2017/11/7.
//
#include <stdlib.h>
#include <unistd.h>
#include <sys/fcntl.h>
#include <time.h>
#include <sys/stat.h>
#include <cstdio>
#define N 10
/**
* 从文件读入数据
* @param fd
* @param num
*/
void readFromFile(int fd,int num[]){
if(fd<0) return;
int fid =dup(STDIN_FILENO);
if(dup2(fd,STDIN_FILENO)<0 && close(fd)<0){
perror("1");
exit(1);
};
for (int i = 0; i < N; ++i) {
scanf("%d\n",&num[i]);
}
if(dup2(STDIN_FILENO,fd)<0 && dup2(fid,STDIN_FILENO)<0 && close(fid)<0){
perror("2");
exit(1);
}
}
/**
* 打印到文件
* @param fd
* @param num
*/
void printfToFile(int fd,int num[]){
int sout_fd = dup(STDOUT_FILENO);
if(dup2(fd,STDOUT_FILENO)<0 && close(fd)<0){
perror("3");
exit(1);
}
for (int i = 0; i < N; ++i) {
printf("%d\n",num[i]);
}
if(fflush(stdout)<0 && dup2(STDOUT_FILENO,fd)<0 && lseek(fd,0,SEEK_SET)<0){
perror("4");
exit(1);
}
dup2(sout_fd,STDOUT_FILENO);
close(sout_fd);
}
/**
* 插入排序
* @param num
*/
void sort(int num[]){
for (int i = 1; i < N; ++i) {
int t = num[i];
int j= i;
while(t < num[j-1] && j-1>=0){
num[j] = num[j-1];
j--;
}
num[j] = t;
}
}
int main(){
srand(time(NULL));
int nums[N];
int nin[N];
int fd = open("in", O_CREAT|O_RDWR,S_IRWXU);
for (int i = 0; i < N; ++i) {
nin[i] = rand()%2000;
}
printfToFile(fd,nin);
int saved_fd = open("out",O_CREAT|O_TRUNC|O_WRONLY,S_IRWXU);
if(fd<0 || saved_fd<0){
perror("Open");
} else{
printf("helloworld\n");
fflush(stdout);
readFromFile(fd,nums);
close(fd);
sort(nums);
printfToFile(saved_fd,nums);
close(saved_fd);
}
}