Weird characters appear after writing to a textfile
I am currently trying to read a file, put extra backward slash () if it finds a backward slash, and write it to another file. The problem is, there are weird characters being printed inside the path.txt
. I suspect that, the space
characters from the file logdata
is the root of this problem. Need advice how to solve this.
Here is the code:
// read a file
char str[256];
fstream file_op("C:\\logdata",ios::in);
file_op >> str;
file_op.close();
// finds the slash, and add additional slash
char newPath[MAX_PATH];
int newCount = 0;
for(int i=0; i < strlen(str); i++)
{
if(str[i] == '\\')
{
newPath[newCount++] = str[i];
}
newPath[newCount++] = str[i];
}
// write it to a different file
ofstream out("c:\\path.txt", ios::out | ios::binary);
out.write(newPath, strle开发者_Go百科n(newPath));
out.close();
Every char string in C has to end with character \0. It is an indicator that the string ends right there.
Your newPath
array, after iterating through your for-loop is not correctly ended. It probably ends somewhere later, where \0 appears by accident in memory.
Try doing the following right after exiting the for-loop:
newPath[newCount]=0;
A safer way for using strings in C++, is to use std::string class over plain char arrays.
Try putting a string terminator in the buffer, after the loop :
newPath[newCount] = 0;
精彩评论