To make your code more efficient, it is better first to read the entire number list from s.fit file, then sort it and extract the requested periods from 3.asc file in a single pass:
#include <stdlib.h>
#include <stdio.h>
#define BUFFER_SIZE 1024
#define NUM 10 // Maximum number of items in s.fit file
#define PERIODNUM 17900
#define LINESPERPERIOD 512
int compare(const int *arg1, const int *arg2)
{
return *arg1 == *arg2 ? 0 : *arg1 < *arg2 ? -1 : 1;
}
void extract() {
const char *filename1 = "C:\\user\\hope\\s.fit";
const char *filename2 = "C:\\user\\hope\\3.asc";
const char *filename3 = "C:\\user\\hope\\3.out";
FILE *input_file_1 = fopen(filename1, "r");
FILE *input_file_2 = fopen(filename2, "r");
FILE *output_file = fopen(filename3, "w");
char buffer[BUFFER_SIZE];
int i = 0, n = 0;
int numbers[NUM];
char* res;
if (input_file_1 == NULL){
fprintf(stderr, "Unable to open file %s\n", filename1);
}
else if (input_file_2 == NULL){
fprintf(stderr, "Unable to open file %s\n", filename2);
}
else {
while (n < NUM && fgets(buffer, BUFFER_SIZE, input_file_1) != NULL)
numbers[n++] = atoi(buffer);
fclose(input_file_1);
qsort(numbers, n, sizeof(int), compare); for (int p = 1; p <= PERIODNUM && i<n; p++) {
if (numbers[i] == p) fprintf(output_file, "Period: %d\n", p);
for (int l = 1; l <= LINESPERPERIOD; l++)
if ((res=fgets(buffer, BUFFER_SIZE, input_file_2)) != NULL) {
if (numbers[i] == p) fputs(buffer, output_file); }
else break;
if (res == NULL) break;
if (numbers[i] == p) i++; }
if (res != NULL) puts("Processing completed successfully\n");
else puts("Not enough lines in 3.asc file\n");
}
fclose(input_file_2);
fclose(output_file);
}
This code is just a sketch of what your final program may look like. You'll need to add proper error processing, for example, as the only error checked here is too short a 3.asc file. Also, it is not clear what data you need to put in the output file so this code sample just puts the entire line from the 3.asc file. You may add necessary processing of this line in the place indicated by the comment.