| 
  • Earn a $50 Amazon gift card for testing a new product from the makers of PBworks. Click here to apply.

  • If you are citizen of an European Union member nation, you may not use this service unless you are at least 16 years old.

View
 

TextEditing

Page history last edited by Kenneth Finnegan 11 years, 9 months ago

This trick is useful when you're expecting a variable number of lines of input from the user and want to let them go back and edit it as they like.  It's also great when you want to have something in the input field to start with, but can be edited as well.

 

Code:

// Initialize what you want the user to be presented with

// This part uses stdio.h for the file io

FILE *fp = fopen("tempfile", "w");

fprintf(fp, "Write your life story here");

fclose(fp); 

// include stdlib.h for system(char *)

system("nano tempfile"); 

// Now read back in the file

 

Usage:

system() is a function that passes the string passed to it to the outside environment.  This is useful because so many other people have put countless hours of development into text editors.  Because of it there is NO reason why you should waste your time with this. 

 

Nano is a unix text editor.  I show using it instead of one of the two major editors (vim or emacs) because it is much more user friendly.  In Windows/DOS, use EDIT.EXE instead (unconfirmed, I don't have a Win compiler).

 


Extensions:

The text editor nano is hard coded in this version, a better implementation would be to make it a macro or string so a user could easily change it to their favorite text editor (ie vim or emacs).

#define TEXT_EDITOR "nano "

system(TEXT_EDITOR "filename");

// NOTE: This uses the string concatenation trick, don't freak out!

////////// OR //////////

char *text_editor = "nano";

char stringbuff[1000];

sprintf(stringbuff, "%s filename", text_editor);

system(stringbuff);

 

Generate a random filename to try and prevent any kind of file collision. 

sprintf(filename, "temp%d.txt", rand());

 

A better way to prevent file collision would be to use the stdio.h function tmpnam():

tmpnam(char *filename);

 


Sources:

The C Programming Language 2nd Ed., Kernighan & Ritchie, pp. 253.

Inspired by bzr.

http://www.cppreference.com/stdio/tmpnam.html

Comments (0)

You don't have permission to comment on this page.