gpt4 book ai didi

c - 两次成功读取后,与 fseek() 一起使用时 fgetc() 不起作用

转载 作者:行者123 更新时间:2023-11-30 17:23:03 25 4
gpt4 key购买 nike

我正在尝试加密(简单位操作算法)一个文件,为此我创建了三个不同的版本

  1. 在加密或解密过程中创建新文件并删除旧文件并重命名
  2. 使用两个不同的 File * 对同一个文件进行加密或解密,一个在 rb 中打开文件,另一个在 rb+< 中打开同一文件
  3. 加密或解密发生在同一个文件上,仅使用一个 FILE*,文件以 rb+ 模式打开。

前两个版本按预期工作,它们不使用 fseek(),但我在版本 3 中遇到问题

v3 代码:

FILE *inputFile= NULL,*outputFile = NULL;

char *inName = "file.txt",*outName;

/* I am using same source file for all three version controlled by #if, so the following assignment is necessary*/
outName = inName;

inputFile = fopen(inName,"rb+");
if(inputFile == NULL)
{
perror(inName);
exit(EXIT_FAILURE);
}

/* I am using same source file for all three version controlled by #if, so the following assignment is necessary*/
outputFile = inputFile;

long int currentLocation;
unsigned char targetChar;
int intChar;
long int offset,temp;

while(currentLocation = ftell(inputFile),(intChar = fgetc(inputFile))!= EOF)
{
targetChar = intChar;

/*#if encryption
encrypt(&targetChar);
#else
decrypt(&targetChar);
#endif // encryption*/

/* going back in the file to the starting position of currently read character*/

temp = currentLocation;
currentLocation = ftell(inputFile);
offset = temp - currentLocation; // the offset is always -1 throughout the program(gdb)

if(fseek(inputFile,offset,SEEK_CUR)==-1)
{
perror(outName);
exit(EXIT_FAILURE);
}
// writing the encrypted or decrpted character to the file
if(fputc(targetChar,outputFile) == EOF)
{
perror(outName);
exit(EXIT_FAILURE);
}
}
fclose(inputFile);
fclose(outputFile);

对于前两个字符,fgetc() 工作正常,但它根本没有读取,同时 currentLocation 正在稳步递增。

如果文件有以下内容

世界你好!!

输出为

Heelo 世界!!

Heeeeeeeeeeeeeeeeeeeeeeeee...

e的数量取决于程序运行的时间,它是一个无限循环。

我正在使用 fseek() 向后移动,即使我只向后移动 fseek() ,这是否会清除 EOF(导致无限循环条件)?我在调试器中检查了 fgetc() 没有读取超过两个字符,但 currentLocation 正在以 1 的增量移动,为什么 fgetc() 没有读取超过两个字符两个字符?

最佳答案

   if(fputc(targetChar,outputFile) == EOF)
{
perror(outName);
exit(EXIT_FAILURE);
}
fflush(outputFile);//need flush
}
fclose(inputFile);
//fclose(outputFile);//double close!

关于c - 两次成功读取后,与 fseek() 一起使用时 fgetc() 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27762574/

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