#include <stdio.h> #include <stdlib.h>
#define MAX_LEN 10 #define M 5 #define N 10
int process_file1(int A[]) { FILE* fp1 = fopen("record_bak.txt","w"); int i = 0; int j = M; char line[MAX_LEN];
while(i<M && j<N) { if(A[i]<A[j]) { sprintf(line, "%d\n", A[i]); fwrite(line, 1, strlen(line), fp1); i++; } else { sprintf(line, "%d\n", A[j]); fwrite(line, 1, strlen(line), fp1); j++; } } if(i==M) { while(j<N) { sprintf(line, "%d\n", A[j]); fwrite(line, 1, strlen(line), fp1); j++; } } else if(j==N) { while(i<M) { sprintf(line, "%d\n", A[i]); fwrite(line, 1, strlen(line), fp1); i++; } } fclose(fp1); }
int process_file2() { FILE* fp = NULL; FILE* fp1 = NULL; FILE* fp2 = NULL; char line1[MAX_LEN]; char line2[MAX_LEN]; int num1 = 0; int num2 = 0; int flag = 0; int i = 0; fp = fopen("record.txt","r"); fp1 = fopen("record_tmp1.txt","w"); fp2 = fopen("record_tmp2.txt","w"); while(fgets(line1, MAX_LEN, fp)) { printf("line is %s",line1); if(i<M) { printf("%d\n",fwrite(line1, 1, strlen(line1), fp1)); i++; } else { printf("%d\n",fwrite(line1, 1, strlen(line1), fp2)); i++; } } fclose(fp); fclose(fp1); fclose(fp2); fp = fopen("record.txt","w"); fp1 = fopen("record_tmp1.txt","r"); fp2 = fopen("record_tmp2.txt","r"); fgets(line1, MAX_LEN, fp1); fgets(line2, MAX_LEN, fp2); while(1) { num1 = atoi(line1); num2 = atoi(line2); if(num1 < num2) { fwrite(line1, 1, strlen(line1), fp); if(!fgets(line1, MAX_LEN, fp1)) { fwrite(line2, 1, strlen(line1), fp); flag = 1; break; } } else { fwrite(line2, 1, strlen(line2), fp); if(!fgets(line2, MAX_LEN, fp2)) { fwrite(line1, 1, strlen(line1), fp); flag = 2; break; } } } if(flag == 1) { while(fgets(line2, MAX_LEN, fp2)) fwrite(line2, 1, strlen(line2), fp); } else if(flag == 2) { while(fgets(line1, MAX_LEN, fp1)) fwrite(line1, 1, strlen(line2), fp); } fclose(fp); fclose(fp1); fclose(fp2); remove("record_tmp1.txt"); remove("record_tmp2.txt"); } int main(int argc, char *argv[]) { int A[N]; int i = 0; FILE* fp = NULL; char line[MAX_LEN]; fp = fopen("record.txt","r"); while(fgets(line, MAX_LEN, fp)) { A[i] = atoi(line); i++; } fclose(fp); process_file1(A); process_file2(A); system("PAUSE"); return 0; }
|