Example for text editing in Linux


This post is example code for an implementation of a feature that will modify a text file, writing changes to the file and replacing it, in the Linux OS environment. It searched for a specific text substring, and modifies that substring based on a user defined variable. I had struggled through this myself because my previous implementation with Juce was writing CR/LF bytes to each line, and my configuration file parser required to only have \n characters to delimit each line. I finally found a way to output the bytes to the text file without CR/LF. This might be a problem unique to Linux using Juce. Props to “cpr” for helping point me to using a hex editor, to identify the extra CR/LF bytes.

This could be useful, for example, if you have an application configuration file in simple text, and want to easily edit a parameter.

I hope this helps anyone, and feel free to comment on this code for any improvements.

// text file
File appConfig;
appConfig = T("conf.txt");

// Check to make sure it exists
if(appConfig.existsAsFile()) {

   // load file into memory as a string
   String currentConfig = appConfig.loadFileAsString();

   // look for string in text file that specifies the GUI_SKIN configuration

      // Get the  length
      int confLen = currentConfig.length();

      // Find the index for where to start reading the colour
      tchar *startStr = T("GUI_SKIN=");;
      int startIndex = currentConfig.indexOf(startStr);
      int endIndex = currentConfig.indexOf(startIndex,T("\n"));
      int startColorStr = startIndex + 9;
      String foundColor = currentConfig.substring(startColorStr,endIndex);
      String foundColorTrim = foundColor.trim();
      // Make sure this isn't the same colour that was there before
      int cmp = strcmp(foundColorTrim,newColor);
      if(cmp == 0){
         printf("Trying to set skin color to %s, which is already set\n",newColor.toUTF8());

      } else {

         // create a new string to hold the modified configuration 
         String newConfig;
         // Replace the colour parameter string and return the new configuration
         newConfig = currentConfig.replace(foundColorTrim,newColor,0);
         confLen = newConfig.length();
         // delete current file

         // create new config file

         // create a new FileOutputStream
         FileOutputStream ofstream(appConfig,confLen);

         // Output the new config string into the file