I have this code:
while( (cCurrent = fgetc(fp)) != EOF)
{
}
The problem is, when it hits a new line it stops reading.
What would be a good way to ignore the newline character?
Edit:
I’m trying to create a file crypter.
It is able to encrypt the file, but the decrypt process won’t work.
It works till the end of the first line, but it won’t continue to the next characters in the file.
For example, for the text file:
Foo
Bar
After the encryption the result is:
Xu||Gb|t
After the decryption the result is:
FooRqb
I concluded that the new line char was the problem. maybe it wasn’t.
My code is:
/* check if the file is openable */
if( (fp = fopen(szFileName, "r+")) != NULL )
{
/* save current position */
currentPos = ftell(fp);
/* get the current byte and check if it is EOF, if not then loop */
while( (cCurrent = fgetc(fp)) != EOF)
{
/* XOR it */
cCurrent ^= 0x10;
/* take the position indicator back to the last position before read byte */
fseek(fp, currentPos, SEEK_SET);
/* set the current byte */
fputc(cCurrent, fp);
/* reset stream for next read operation */
fseek(fp, 0L, SEEK_CUR);
/* save current position */
currentPos = ftell(fp);
}
On Windows, lines in text files are separated by
\r\n, not just\n, and files are opened by default in “text” mode, which automatically translates\r\nto\nwhen reading the file (see fopen in Visual Studio 2012).Since you’re interpreting your file as a sequence of bytes (because of the XOR operation), you don’t want this behavior – each time there is a line ending, you’re losing a byte of data. You should open your file in “binary” mode to suppress this behavior:
This will also suppress the behavior noted by @Mike where reading a
\x1Acharacter is interpreted as the end of file.