Hello all, I have a text file which contains words and punctuations like. I tried to use read() to read all the characters in the text file all at one. But when I tried to check the number of characters in the file, it said that it's can only read some of the characters and when i print all the characters in another text file there are some characters that are not in the input file.
The stream requires a null terminator, you are reading in the files length of say 14, allocating memory for 14 characters but since the memory address after that will be garbage (and most likely not null) it will write random rubbish until it finds one.
You also don't have any error checking, what happens if your program cant find the input.txt
The discrepancy is probably related to the number of lines in the text file. in text mode, some translation of the line-ending sequence (on windows "\r\n" to "\n") may take place. If the file contains ordinary text, this is probably not a reall problem.
One other comment. Line 23 fout<<buffer; looks risky. It is treating the buffer as a null-terminated character string, however there is no guarantee that there will actually be a null found. For safety, you should allocate the buffer with one extra byte. After the read at line 12, buffer[ fin.gcount()] should be set to zero.
Line 23 works on a null-terminated string. You haven't added a null character to the end of the string.
But this will only work if your input file doesn't contain a null character. If it does contain a null character, then line 23 will write to that character only.
So you need to use write() instead. fout.write(buffer, length);
As for the number of characters, try opening the file in binary mode. I *think* that in text mode, the only thing you can reliably use tellg()'s output for is as input to seekg(): fin.open("input.txt", ios_base::binary);