Click here to Skip to main content
15,031,680 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to show all content of a text file using “read” method in output.
I have used code below for doing this:

But it was shown some special characters in the end of file content which you can see below:

C++
ÍÍýýýý««««««««îþîþîþ


What’s the reason? I don’t want this.

What I have tried:

C++
#include
#include
#include
using namespace std;

int main(){

ifstream myfile;
myfile.open("c:\\new.txt", ios::in);
myfile.seekg(0, ios::end);
int filesize = myfile.tellg();
char *content = new char[filesize + 1];
myfile.seekg(0, ios::beg);
myfile.read(content, filesize);
content[filesize] = '\0';
cout << content;
delete[] content;
myfile.close();

_getch();
return 0;

}

File content:
this is a test
this is a test
Posted
Updated 21-Feb-16 23:20pm
v3

That is because you have not added a null character to tell cout where the end of the buffer is. Try:
C++
int filesize = myfile.tellg();
char *content = new char[filesize + 1];  // add space for null character
myfile.seekg(0, ios::beg);
myfile.read(content, filesize);
content[filesize] = '\0';    // mark end of text

Note this code is over simplified.
   
Comments
Pouria Polouk 21-Feb-16 13:40pm
   
The problem is still there.
But the number of special characters is decreased!
Richard MacCutchan 21-Feb-16 13:52pm
   
You must still be doing something wrong, but you need to show us the exact code you are using, and the content of your file (assuming it is only very small).
Pouria Polouk 21-Feb-16 14:00pm
   
#include<iostream>
#include<conio.h>
#include<fstream>
using namespace std;

int main(){

ifstream myfile;
myfile.open("c:\\new.txt", ios::in);
myfile.seekg(0, ios::end);
int filesize = myfile.tellg();
char *content = new char[filesize + 1];
myfile.seekg(0, ios::beg);
myfile.read(content, filesize);
content[filesize] = '\0';
cout << content;
delete[] content;
myfile.close();

_getch();
return 0;

}

File content:
this is a test
this is a test
The problem occurs because you are reading a textfile, and as fstream processes the content it replaces CR-LF sequences with the single newline character '\n'. Thus your actual content will be shorter than the length of the file on disk. You should use the getline method to read each line of the file in turn, or set the file type to binary (see ios_base::openmode[^]).
   
Comments
Pouria Polouk 22-Feb-16 9:40am
   
I don't want to use getline method.
thank you so much... solved(ios::binary).

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900