gpt4 book ai didi

c - 尝试从文件中读取时无限循环

转载 作者:行者123 更新时间:2023-12-01 22:53:00 24 4
gpt4 key购买 nike

我想从文件中读取字节然后重写它们。我确实喜欢这样:

FILE *fp;
int cCurrent;
long currentPos;

/* check if the file is openable */
if( (fp = fopen(szFileName, "r+")) != NULL )
{
/* loop for each byte in the file crypt and rewrite */
while(cCurrent != EOF)
{
/* save current position */
currentPos = ftell(fp);
/* get the current byte */
cCurrent = fgetc(fp);
/* XOR it */
cCurrent ^= 0x10;
/* take the position indicator back to the last position */
fseek(fp, currentPos, SEEK_SET);
/* set the current byte */
fputc(cCurrent, fp);
}

在文件上执行代码后,文件的大小在无限循环中增加。

我的代码有什么问题?

最佳答案

您正在用 0x10 XOR-ing cCurrent,即使它等于 EOF。一旦你XOR,它就不再是EOF,所以你的循环永远不会终止。

无限循环,看到EOF就从中间退出,像这样:

for (;;)  {
/* save current position */
currentPos = ftell(fp);
/* get the current byte */
if ((cCurrent = fgetc(fp)) == EOF) {
break;
}
/* XOR it */
cCurrent ^= 0x10;
/* take the position indicator back to the last position */
fseek(fp, currentPos, SEEK_SET);
/* set the current byte */
fputc(cCurrent, fp);
/* reset stream for next read operation */
fseek(fp, 0L, SEEK_CUR);
}

关于c - 尝试从文件中读取时无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13271755/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com