试图了解ftell函数的返回值

#include<stdio.h> #include<string.h> int main() { long int count; FILE *file=NULL; file=fopen("sample.txt","r+"); if(file==NULL) { printf("file open fail\n"); return; } printf("file open succesfull\n"); if(0!=fseek(file,1,SEEK_END)) { printf("seek failed\n"); return; } printf("seek successful\n"); count=ftell(file); printf("%lu", count); return 0; } 

产量

 file open succesfull seek successful 3 

我的smaple.txt文件只有一个字符,那就是q。 为什么在这里展示3? 另外,当我有文件为空,然后ftell()返回1,那是什么?
在Ubuntu的12.04工作

您的fseek(file, 1, SEEK_END)将位置放在文件末尾以外的一个字符处。 这就解释了为什么你会把这个空白文件当作一个数字。 我猜你的文件,只包含aq,也包含实际上是两个字符的回车。 在最后的字符是3,你观察到的。

您不正确地使用fseek()通过ftell()来确定文件的大小。

man fseek() (由我斜体 ):

int fseek(FILE * stream,long offset,int whence);

[…]以字节为单位的新位置是通过将偏移字节添加到由此指定的位置来获得

这一行:

 if(0!=fseek(file,1,SEEK_END)) 

文件结束 1个字节的文件指针定位。

要解决这个问题:

 if (0 != fseek(file, 0, SEEK_END)) 

你错误地解释了ftell和fseek函数。 减少咖啡更多的休息:第

完全手册页

长时间(FILE *流);

ftell()函数获取流指向的流的文件位置指示符的当前值。

fseek手册页

int fseek(FILE * stream,long offset,int whence);

fseek()函数设置流指向的流的文件位置指示符。 以字节为单位的新位置是通过将偏移字节添加到由此指定的位置来获得的。 如果将其设置为SEEK_SET,SEEK_CUR或SEEK_END,则偏移量分别与文件起始位置,当前位置指示符或文件结束相关。 成功调用fseek()函数将清除流的文件结尾指示符,并取消同一个流上的ungetc(3)函数的任何效果。

创建sample.txt

echo -n'q'> sample.txt

文件查找示例

 #include <stdio.h> #include <stdlib.h> int main( int argc, char** argv ) { FILE* file = fopen( "sample.txt", "r" ); if( NULL == file ) { perror("Failed to open file"); return EXIT_FAILURE; } printf("File successfully opened\n"); long position = ftell( file ); printf( "Position before seek: %lu\n", position ); int status = fseek( file, 1L, SEEK_SET ); if( 0 != status ) { perror("Failed to seek"); return EXIT_FAILURE; } printf("File seek successful\n"); position = ftell( file ); printf( "Position after seek: %lu\n", position ); return EXIT_SUCCESS; } 

文件大小示例

 #include <stdio.h> #include <stdlib.h> #include <sys/stat.h> int main( int argc, char** argv ) { struct stat file_status = { 0 }; int status = stat( "sample.txt", &file_status ); if ( 0 != status ) { perror("Failed to read file status"); return EXIT_FAILURE; } printf( "File size: %li\n", file_status.st_size ); return EXIT_SUCCESS; } 

建立

gcc -o example example.c