[solved] Reading text files of unknown length returns garbage

Hello there,
I had my whole program running on String untill I learned that String is not the proper way to do it and that character arrays are way more faster and efficient.

In doing so, A problem arised where I need to read a file whose file size is unknown. The end of the file is full of garbage values when I read it . I have to upload its contents to my webserver and I dont want to upload garbage. I tried to replace them with the ‘\0’ but the code just freezes the arduino.

Following is the code I used

  File dataFile = SD.open("log.txt");
  char text [250];
  int i = 0;
  if (dataFile) 
  {
    while (dataFile.available()) 
    {
      text[i] = dataFile.read(); i++;
    }
    while (i <= 249)
    {
      text[i] = '\0';
    }
    dataFile.close();
    Serial.println(text);
  }
  else {
    Serial.println("error opening datalog.txt");
  }

I would appreciate a lot if someone could help me out.
Thanks a lot in advance

I solved it myself, I read on a post on StackOverFlow that a '\0' is needed at the end of the character array to terminate it. So I just edited my code to just do that.

This is the code that worked for me

  File dataFile = SD.open("log.txt");
  char text [260];
  int i = 0;
  if (dataFile)
  {
    while (dataFile.available())
    {
      text[i] = dataFile.read(); i++;
      text[i] = '\0';
    }
    dataFile.close();
    Serial.println(text);
  }
  else {
    Serial.println("error opening datalog.txt");
  }

If you're going to run it with unknown file sizes, this is a problem:

    while (dataFile.available()) 
    {
      text[i] = dataFile.read(); i++;
    }

You need to add a check that you're not writing off the end of the array.