Other Functions

Now that we've defined the callback functions, we need our support functions to make it all work:

check_save()

This function checks to see if the current file needs to be saved. If so, it asks the user if they want to save it:

int check_save(void) {
  if (!changed) return 1;

  if (fl_ask("The current file has not been saved.\n"
             "Would you like to save it now?")) {
    // Save the file...
    save_cb();

    return !changed;
  }
  else return (1);
}
       

load_file()

This function loads the specified file into the input widget:

void load_file(char *newfile) {
  FILE *fp;
  char buffer[8192];
  int  nbytes;
  int  pos;

  input->value("");

  fp = fopen(newfile, "r");
  if (fp != NULL) {
    // Was able to open file; let's read from it...
    strcpy(filename, newfile);
    pos = 0;

    while ((nbytes = fread(buffer, 1, sizeof(buffer), fp)) > 0) {
      input->replace(pos, pos, buffer, nbytes);
      pos += nbytes;
    }

    fclose(fp);
    input->position(0);
    set_changed(0);
  } else {
    // Couldn't open file - say so...
    fl_alert("Unable to open \'%s\' for reading!");
  }
}
        

When loading the file we use the input->replace() method to "replace" the text at the end of the buffer. The pos variable keeps track of the end of the buffer.

save_file()

This function saves the current buffer to the specified file:

void save_file(char *newfile) {
  FILE *fp;

  fp = fopen(newfile, "w");
  if (fp != NULL) {
    // Was able to create file; let's write to it...
    strcpy(filename, newfile);

    if (fwrite(input->value(), 1, input->size(), fp) < 1) {
      fl_alert("Unable to write file!");
      fclose(fp);
      return;
    }

    fclose(fp);
    set_changed(0);
  } else {
    // Couldn't open file - say so...
    fl_alert("Unable to create \'%s\' for writing!");
  }
}
        

set_changed()

This function sets the changed variable and updates the window label accordingly:

void set_changed(int c) {
  if (c != changed) {
    char title[1024];
    char *slash;

    changed = c;

    if (filename[0] == '\0') strcpy(title, "Untitled");
    else {
      slash = strrchr(filename, '/');
      if (slash == NULL) slash = strrchr(filename, '\\');

      if (slash != NULL) strcpy(title, slash + 1);
      else strcpy(title, filename);
    }

    if (changed) strcat(title, " (modified)");

    window->label(title);
  }
}