gpt4 book ai didi

c - Getc 过度读取一个\n 字符

转载 作者:太空宇宙 更新时间:2023-11-04 07:56:22 25 4
gpt4 key购买 nike


我在使用这个可以读取文件的小函数时遇到了一些问题:

void ReadFile(char *name) {
FILE *fr;
int lenght, i;
fr = fopen(name, "r"); //Open the file reader
fseek(fr, 0, 2); //Set the pointer at the EOF
lenght = ftell(fr); //Read the ending position
printf("\nDEBUG lenght:%d\n", lenght);
fseek(fr, 0, 0); //Return at the beginning of the file

printf("File read:\n\n");
for (i = 1; i <= lenght; i++) {
printf("%c", getc(fr));
fseek(fr, i, 0);
}
fclose(fr);
}

这是它读取的文件:

qwerty

asdfgh
zxcvbn

但这是程序的输出:

DEBUG lenght:24
File read:

qwerty



asdfgh

zxcvbn

基本上就是在前面有一个"\n"的时候多读一个"\n"。
关于为什么代码不起作用的任何想法?

谢谢

最佳答案

如果您以文本模式打开文件(像您一样),则调用 fseek可能只包含先前由 ftell 检索到的偏移值函数(参见,例如 cppreference/fseek ):

If the stream is open in text mode, the only supported values for offset are zero (which works with any origin) and a value returned by an earlier call to ftell on a stream associated with the same file (which only works with origin of SEEK_SET).

在你的for -loop,但是,您正在传递 i 的值, 未被 ftell 检索到.

除此之外,您的 fseek在循环中是多余的,如fgetc无论如何向前移动读指针。所以for (i = 1; i <= lenght; i++) { printf("%c", getc(fr)); }应该完成这项工作。

关于c - Getc 过度读取一个\n 字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49865369/

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