A common requirement of many text editors is the ability to read text from a file, allow the user to edit the text, and then store the text in a file. An application usually obtains pathnames from the user by means of a FileSelectionBox, often invoked as a dialog from a MenuBar File Menu. Following are very simple routines that use ANSI C input/output facilities to read text from a file into a Text widget and save text from a Text widget into a file:
void ReadTextFromFile(Widget w, char *filename)
{
FILE *file;
char buffer[MAXSIZE];
char *ptr, *end;
XmTextPosition last_pos;
int val;
if (file = fopen(filename, "r")) {
XmTextSetString(w, "");
ptr = buffer;
end = buffer + MAXSIZE - 1;
while((val = getc(file)) != EOF) {
if (ptr < end) {
*ptr++ = (char) val;
} else {
*ptr = '\0';
last_pos = XmTextGetLastPosition(w);
XmTextReplace(w, last_pos, last_pos, buffer);
ptr = buffer;
}
}
if (ptr > buffer) {
*ptr = '\0';
last_pos = XmTextGetLastPosition(w);
XmTextReplace(w, last_pos, last_pos, buffer);
}
(void) fclose(file);
}
}
void SaveTextToFile(Widget w, char *filename)
{
FILE *file;
char *text;
if (file = fopen(filename, "w")) {
text = XmTextGetString(w);
(void) fputs(text, file);
(void) fclose(file);
XtFree(text);
}
}