[haiku-development] Re: Help reading text file.

  • From: richard jasmin <jasminr@xxxxxxxxxxx>
  • To: haiku-development@xxxxxxxxxxxxx
  • Date: Sun, 03 Aug 2008 11:03:16 -0400

not a C/C++ expert, but this seems to be a common issue.
it was discovered with dos/unix text file conversion.

try string=string[:-1] or something like that.you have to take off the leading one or two whitespace characters.i have to do it with python sometimes.

Fredrik Modéen wrote:
Hi
Anyone good at how to read text files in BeOS/Haiku?

I'm trying to read one line at a time from a joystick description text
file (/boot/home/config/settings/joysticks).

I have some code that nearly works but not close enough as it contains
text that are not shown as text but square.

this is the code.
status_t
_BJoystickTweaker::get_info(_joystick_info* info, const char * ref)
{
 CALLED();
 LOG("ref = %s\n", ref);
 LOG("============== Begin ==========\n");
 status_t err = B_ERROR;
 BString str(JOYSTICKPATH);
 str.Append(ref);
 LOG("Path = %s\n", str.String());

 BFile file(str.String(), B_READ_ONLY);
 if (file.InitCheck() == B_OK) {
   str = "";
   while (GetLine(&file, B_UNICODE_UTF8, str, true)) {
     LOG("Path = %s\n", str.String());
     if (str.IFindFirst("module") != -1) {
       str.RemoveFirst("module = ");
       str.RemoveAll("\"");
       strncpy(info->module_name, str.String(), STRINGLENGTHCPY);
       LOG("%s\n", str.String());
     } else if (str.IFindFirst("gadget") != -1) {
       str.RemoveFirst("gadget = ");
       str.RemoveAll("\"");
       strncpy(info->controller_name, str.String(), STRINGLENGTHCPY);
       LOG("%s\n", str.String());
     } else {
       LOG("Path = %s\n", str.String());
     }
   }
 }
 LOG("============= End ===========\n");
 err = B_OK;
 return err;
}


bool
_BJoystickTweaker::GetLine(BFile *file, uint32 encoding, BString& str,
bool useConvertUTF8)
{
 BString temp;
 static char buffer[4096];
 static off_t positionInBuffer;
 static ssize_t amt_read;
 str = "";    // Clear out old string
 // Fill up the buffer with the first chunk of code
 if (positionInBuffer == 0)
  amt_read = file->Read(&buffer, sizeof(buffer));
 while (amt_read > 0) {
  while (positionInBuffer < amt_read) {
  // Return true if we hit a newline or the end of the file
    if (buffer[positionInBuffer] == '\n') {
      positionInBuffer++;
      //Convert begin
      int32 state = 0;
      int32 bufLen = str.Length();
      int32 destBufLen = bufLen;
      char dest[destBufLen];
      if (useConvertUTF8)
       convert_to_utf8(encoding, str.String(), &bufLen, dest, &destBufLen,
&state);
      str = dest;
      //Convert ends
      return true;
    }
    str += buffer[positionInBuffer];
    positionInBuffer++;
  }

  // Once the buffer runs out, grab some more and start again
  amt_read = file->Read(&buffer, sizeof(buffer));
  positionInBuffer = 0;
 }
 return false;
}



Other related posts: