Lion King
Lion King

Reputation: 33813

Read unknown symbols when read a content of file

As in the title, when read a content of file i find it reads unknown symbols with the content.

The code:

char *buff = NULL;
size_t size = 0;    
ifstream file("c:\\file.txt", ios::out);

if(!file){
    cout << "File does not open." << endl;
}

file.seekg(0, file.end);
size = file.tellg();
file.seekg(0, file.beg);

buff = new char[size];
while(!file.eof()){
    file.read(buff, size);
}

cout << buff << endl;
delete[] buff;

The file content:

Hello world!. Thank you for help.

The result:

As you seen in the previous image, there are many unknowns symbols.
Why these symbols appear, what's wrong in my code ?

Upvotes: 0

Views: 897

Answers (2)

user657267
user657267

Reputation: 21000

Your char array is not null terminated, either create the array with space for one extra null character (and set it to '\0')

buff = new char[size + 1];
buff[size] = '\0';
// Or simply
buff = new char[size + 1]{};

or even better avoid using raw pointers wherever possible, especially for character arrays used as strings.

while(!file.eof()) is an antipattern, don't use it except in very specific cases.

std::ifstream file("file.txt");
std::string buff{ // Use regular brackets if not C++11
  std::istreambuf_iterator<char>(file),
  std::istreambuf_iterator<char>()
};

Upvotes: 3

David Schwartz
David Schwartz

Reputation: 182769

You can only use operator<<(const char *) for C-style strings. You can't use it for arbitrary chunks of bytes. How would it know where to stop?

Upvotes: 1

Related Questions