📜  门| GATE CS 2018 |问题 19(1)

📅  最后修改于: 2023-12-03 15:42:11.881000             🧑  作者: Mango

GATE CS 2018 - Problem 19

This is a problem from the GATE CS 2018 exam. It is a question about programming and computer science.

The Problem

The problem asks to write a program to simulate reading and writing to a file using the fread and fwrite functions in C. The program must read a file named input_data.bin containing 1000 long integers, sort them in ascending order, and write the sorted integers to a file named output_data.bin.

The Solution
#include <stdio.h>
#include <stdlib.h>

int main() {
  long int data[1000];
  FILE *input_file, *output_file;

  // Open input file
  input_file = fopen("input_data.bin", "rb");
  if (input_file == NULL) {
    printf("Error: Cannot open input file.\n");
    exit(1);
  }

  // Read data from input file
  fread(data, sizeof(long int), 1000, input_file);
  fclose(input_file);

  // Sort data in ascending order
  qsort(data, 1000, sizeof(long int), compare);

  // Open output file
  output_file = fopen("output_data.bin", "wb");
  if (output_file == NULL) {
    printf("Error: Cannot open output file.\n");
    exit(1);
  }

  // Write data to output file
  fwrite(data, sizeof(long int), 1000, output_file);
  fclose(output_file);

  return 0;
}

int compare(const void *a, const void *b) {
  return (*(long int*)a - *(long int*)b);
}

This program defines an array of 1000 long integers, and two FILE pointers to open the input and output files. The program first opens the input file in binary mode, reads the contents of the file with fread, sorts the data using the qsort function with a custom comparison function, opens the output file in binary mode, and writes the sorted data with fwrite.

The program also checks for errors when opening the files, and uses a custom comparison function for the qsort function.

Conclusion

This program is a solution to the GATE CS 2018 problem 19. It shows how to read and write binary files in C using the fread and fwrite functions, and how to sort an array of long integers using the qsort function with a custom comparison function.