/* nag_open_file (x04acc) Example Program.
 *
 * NAGPRODCODE Version.
 *
 * Copyright 2016 Numerical Algorithms Group.
 *
 * NAG C Library
 *
 * Mark 26, 2016.
 *
 */

#include <stdio.h>
#include <string.h>
#include <nag.h>
#include <nag_stdlib.h>
#include <nagx04.h>

int main(void)
{
  Integer mode, exit_status = 0;
  Nag_FileID fileid;
  const char *filename;
  char line[100], line2[100];
  NagError fail;

  INIT_FAIL(fail);

  printf("nag_open_file (x04acc) Example Program Results\n");
  printf("\n");

  filename = "x04acc_example.txt";
  printf("Attempting to write to and read from file %s:\n", filename);

  /* Open the file for writing */
  mode = 1;
  /* nag_open_file (x04acc).
   * Open unit number for reading, writing or appending, and
   * associate unit with named file
   */
  nag_open_file(filename, mode, &fileid, &fail);
  if (fail.code != NE_NOERROR) {
    printf("Error from nag_open_file (x04acc) %s\n", fail.message);
    exit_status = 1;
    goto END;
  }
  /* Write a line to the file we opened */
  sprintf(line, "%s", "NAG nag_open_file (x04acc) example program");
  /* nag_write_line (x04bac).
   * Write formatted record to external file
   */
  nag_write_line(fileid, line);
  /* Close the file */
  /* nag_close_file (x04adc).
   * Close file associated with given unit number
   */
  nag_close_file(fileid, &fail);
  if (fail.code != NE_NOERROR) {
    printf("Error from nag_close_file (x04adc) %s\n", fail.message);
    exit_status = 1;
    goto END;
  }

  /* Open the file for reading */
  mode = 0;
  /* nag_open_file (x04acc), see above. */
  nag_open_file(filename, mode, &fileid, &fail);
  if (fail.code != NE_NOERROR) {
    printf("Error from nag_open_file (x04acc) %s\n", fail.message);
    exit_status = 1;
    goto END;
  }
  /* Read the line back from the file */
  /* nag_read_line (x04bbc).
   * Read formatted record from external file
   */
  nag_read_line(fileid, line2, 100, &fail);
  if (fail.code != NE_NOERROR) {
    printf("Error from nag_read_line (x04bbc) %s\n", fail.message);
    exit_status = 1;
    goto END;
  }

  if (!strcmp(line, line2))
    printf("\n - correctly wrote line:\n      \"%s\"\n"
           "   to file and read it back.\n", line);
  else {
    printf("\n - failed to write line:\n      \"%s\"\n"
           " to file and read it back.\n", line);
    exit_status = 1;
  }

END:
  return exit_status;
}