Lio*_*ior 2 c newline file fgetc
我有这个代码:
while( (cCurrent = fgetc(fp)) != EOF)
{
}
Run Code Online (Sandbox Code Playgroud)
问题是,当它遇到一个新行时,它会停止阅读.
什么是忽略换行符的好方法?
编辑:
我正在尝试创建一个文件控制器.它能够加密文件,但解密过程不起作用.它一直工作到第一行结束,但它不会继续到文件中的下一个字符.
例如,对于文本文件:
Foo
Bar
Run Code Online (Sandbox Code Playgroud)
加密后,结果是:
徐||千兆| T
解密后,结果是:
Run Code Online (Sandbox Code Playgroud)FooRqb
我得出结论,新线char是问题所在.也许不是.
我的代码是:
/* 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);
}
Run Code Online (Sandbox Code Playgroud)
我花了一段时间,但我终于得到了你想做的事情.
输入文件:
Hello
Run Code Online (Sandbox Code Playgroud)
通过运行代码加密:
Xu||(non displayable character)
Run Code Online (Sandbox Code Playgroud)
通过再次运行代码解密:
Hello
Run Code Online (Sandbox Code Playgroud)
那么这是如何工作的:
0x48 XOR 0x10 = 0100 1000 (H)---+
0001 0000 |
--------- V
0101 1000 = 58 (X)
0x58 XOR 0x10 = 0101 1000 (X)---+
0001 0000 |
--------- V
0100 1000 = 48 (H)
Run Code Online (Sandbox Code Playgroud)
问题在于您使用的新行字符'\n'为0xA 16
输入文件:
Hello
You
Run Code Online (Sandbox Code Playgroud)
这工作正常,直到'\n'我们得到新的行:
0xA XOR 0x10 = 0000 1010 ('\n')---+
0001 0000 |
--------- V
0001 1010 = 1A (substitute character)
Run Code Online (Sandbox Code Playgroud)
替换字符在DOS操作系统中,此字符用于指示文件的结尾(EOF)
所以这失败是因为你在Windows上工作.因此,您需要对'\n'加密/解密中的案例进行特殊检查,而不是盲目地对其进行异或.
一个简单的解决方法,你可以简单地做一些事情:
while( (cCurrent = fgetc(fp)) != EOF)
{
/* XOR it if it's not a '\n'*/
if(cCurrent != '\n')
cCurrent ^= 0x10;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10551 次 |
| 最近记录: |