0

I have some code to read data from files, but when I run this code, it's returning more than I expected. Can someone help me to fix that?

Txt file:

test_line1
test_line2
test_line3

Console output:

test_line1
test_line2
test_line3rs\pc\█×u«║2

Code:

#include <iostream>
#include <fstream>

using namespace std;

char *getDataFromFile(char *file_patch)
{
 fstream file;
 
 file.open(file_patch, ios::in | ios::binary);

 if (file.is_open())
 {
  file.seekg(0, file.end);
  int length = file.tellg();
  file.seekg(0, file.beg);

  char *data = new char[length];

  file.read(data, length);
  
  file.close();
  return data;
 }
 file.close();
}

int main(int argc, char **argv)
{ 
 cout << getDataFromFile("test.txt") << endl;
 system("PAUSE");
 return 0;
}

I was trying to create a void function with addres in input, but still it is not working.

Also, I tried to create a char table instead of char array, it worked but I couldn't return it anymore.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
elo_melo
  • 23
  • 4
  • 2
    Your string doesn't end with a `\0`, and thus `cout` gets some data what follows in the memory. Make it `char *data = new char[length+1];` and `data[length]=0;`. – tevemadar Mar 31 '23 at 17:32
  • What happens if your file was not open? Remember it's undefined behavior to not return a value from all code paths of a function. Maybe you want to return `nullptr` or throw an exception. Also `file.close();` is not needed at all. When the destructor is called the file is closed automatically for you. – drescherjm Mar 31 '23 at 17:36
  • this file is not finished yet, and I wanted to check if everything works fine, but thanks – elo_melo Mar 31 '23 at 17:39
  • 2
    1) Why are you not using something that has officially been part of C++ for 25+ years, and that is `std:::string`? 2) What do you return if the file cannot be opened? -- *this file is not finished yet* -- Thus cannot be tested correctly due to the undefined behavior that occurs. – PaulMcKenzie Mar 31 '23 at 17:51
  • Don't return the file data as a `char*`, return it as a `std::string` instead. See [How do I read an entire file into a std::string in C++?](https://stackoverflow.com/questions/116038/) – Remy Lebeau Mar 31 '23 at 22:30

1 Answers1

0

Simple answer: You are using a pointer to a char (char *) to return what is expected to be a null terminated string (last character is /0). However, the pointer you are returning is not guaranteed to be null terminated.

As mentioned in comments to your question, either allocate length + 1 and set the last character to 0 (not '0') before filling the buffer, or use std::string to store the information.

Also mentioned above: The function is malformed because it returns nothing at all in the case where the file could not be opened.

One last thought: If you see character printed out that are unexpected, you have almost always run past the end of your buffer.

Mikel F
  • 3,567
  • 1
  • 21
  • 33