0

Im able to copy the entire content of say file A to file B but the last line of file B end with several unwanted tttttt. I suspected the number of "t" is related to the number of line if read and written. Any advise will be greatly appreciated.

file A
[TEX]sdakodjskfjsdkfjasook
sample1. : 0987654321
ofjsdfjasfjsdkf
dflsdj

sample1. :[/TEX]

file B
[TEX]sdakodjskfjsdkfjasook
sample1. : 0987654321
ofjsdfjasfjsdkf
dflsdj

sample1. :ÍÍÍÍÍÍÍ[/TEX]

My code;

char * fbuffer;
long fsize;
ifstream cpy ("sample.txt");
ofstream target (finaldir.c_str());
cpy.seekg(0,ifstream::end);
fsize=cpy.tellg();
cpy.seekg(0);
fbuffer = new char [fsize];
cpy.read (fbuffer,fsize);
target.write (fbuffer,fsize);
delete[] fbuffer;
target.close();
4
Contributors
6
Replies
7
Views
9 Years
Discussion Span
Last Post by integer*09
0

No. You are getting some garbage values.

To avoid this make sure last content of the file is '\0'.
simply write '\0' to end of the file.

0

You need to open the file in binary mode in order to prevent CR/LF translation.

char * fbuffer;
long fsize;
ifstream cpy ("sample.txt", [B]ios::binary[/B]);
...

Writing a '\0' at the end of file does not fix the problem.

0

Try this,

char * fbuffer;
long fsize;
ifstream cpy ("sample.txt");
ofstream target (finaldir.c_str());
cpy.seekg(0,ios::end);
fsize=cpy.tellg();
cpy.seekg(0,ios::beg);
fbuffer = new char [fsize+1];
cpy.read (fbuffer,fsize);
fbuffer[fsize]='\0';
target.write (fbuffer,fsize);
delete[] fbuffer;
target.close();[/B]

0

Thanks RenjithVR,

I will try it out when i get back to my desktop, currently on the run with my laptop.

Thanks mitrmkar,

I think i have missed the ios::binary out, i try it when i get back.

0

the simplest (and the most efficient) way to copy a text file (C++):

std::ifstream srce( inputfilename ) ;
  std::ofstream dest( outputfilename ) ;
  dest << srce.rdbuf() ;

if the escape sequence encodings are the same for both files (for instance they are on the same file system), you can squeeze a few cpu cycles by specifying std::ios::binary .

0

Thanks to all who reply,

I have used the ios::binary and its copied perfectly.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.