对于这个可以读取文件的小函数,我有一些问题:
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“,当有一个之前。
对为什么代码不能工作有什么想法吗?
谢谢
发布于 2018-04-16 20:14:24
如果以文本模式打开文件(正如您所做的那样),那么对fseek的调用可能只包含以前由ftell函数(例如,偏好/寻求)检索的偏移量值:
如果流是在文本模式下打开的,则偏移量的唯一受支持值是零(该值适用于任何源),以及在与同一文件关联的流上调用ftell返回的值(该值仅适用于SEEK_SET原点)。
但是,在for-loop中,您传递的是i的值,ftell没有检索该值。
除此之外,循环中的fseek是超灵活的,因为fgetc将读取指针向前移动。所以for (i = 1; i <= lenght; i++) { printf("%c", getc(fr)); }应该做好这项工作。
发布于 2018-04-17 05:30:44
下列拟议守则:
现在,拟议的守则:
#include <stdio.h> // EOF, fopen(), getc(), putc() fclose() puts() perror()
#include <stdlib.h> // exit(), EXIT_FAILURE
// prototype
void ReadFile(char *filename);
void ReadFile(char *filename)
{
FILE *fp = fopen( filename, "r" );
if( !fp )
{
perror( "fopen failed" );
exit( EXIT_FAILURE );
}
// implied else, fopen successful
puts("File read:\n");
int ch;
while( (ch = getc( fp )) != EOF )
{
putchar( ch );
}
fclose(fp);
}https://stackoverflow.com/questions/49865369
复制相似问题