File outputs strange characters

Hello. I have recently been working with files, and the console outputs strange characters upon compilation. The file also outputs the wrong size of my text file, 32 instead of 30.

main.cpp:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <iostream>
#include <string>
#include <fstream>
using namespace std;

int main()
{

	fstream writeFile;
	string fileName = "testing1.txt";

	writeFile.open(fileName, ios::in | ios::binary | ios::ate);

	if (writeFile.is_open())
	{
		int fileSize = writeFile.tellg();

		cout << fileSize << endl; // Returns 32, instead of 30

		char *buffer = new char[fileSize];

		writeFile.seekg(0, ios::beg);

		writeFile.read(buffer, fileSize);

		cout << buffer << endl;

		delete[]buffer; 

		writeFile.close();
	}

	else {
		cout << "File " << fileName << " failed to open" << endl;
	}

	cin.get();
	return 0;
}


testing1.txt:
1
2
3
John Cena
Bob Jones
Katy Perry
C-style strings (char arrays) must be null-terminated when being printed. Null termination is how it determines how long a string is.

Make your buffer's length be 1 character larger than the actual fileSize so that it can store a null character.
e.g.
1
2
char *buffer = new char[fileSize+1];
buffer[fileSize] = '\0';


The file also outputs the wrong size of my text file, 32 instead of 30.

How are you determining what the "correct" file size is? Right-click your file and check its properties. Windows newlines are often two characters (\r\n).
Last edited on
Your statement that "the console outputs strange characters upon compilation" is meaningless without further elaboration. It would seem you are saying when you compile the file (with what compiler?) from the "console", "strange characters" (like what?) are displayed.

You didn't say how the file was created in the first place. And you didn't say what system you are on. However, someone who says "console" is usually a windows person. So, assuming you created the file with "notepad" and didn't put a newline at the end of the last line, then the file contents you show would contain consist of 32 bytes since the windows newline sequence is character code 13 followed by character code 10 (and you opened the file in binary mode, so these won't be translated to a single '\n').
Last edited on
I assumed he meant "upon running the program", because many IDEs will compile + run automatically. But good catch, because TheDomesticHacker2 should know that proper terminology is important and can help clear confusion.
I didn't even notice at first that the program was printing the buffer, so you must be correct about the missing null terminator in the C-style string causing the "strange characters".
Registered users can post here. Sign in or register to post.