繁体   English   中英

用fseek计数文件字符

[英]counting file characters with fseek

我想像这样计算文件字符数:

#include <stdio.h>
#include <stdlib.h>

int main(){
    int d=0;
    char filename[25];
    FILE *file;
    printf("Enter file name to be read (Text File!) : ");
    gets(filename);
    file = fopen(filename, "rt");
    if(file == NULL){
        printf("Failed to open file...");
        exit(1);
    }
    fseek(file, 0L, SEEK_SET);
    while( !feof(file) ){
        fseek(file, 1L, SEEK_CUR);
        d++;
    }
    printf("%d", d);
}

之后,我IM打印D,它的值为0 ..和文件剂量有字符。 约150个字符

fseek()允许您寻求EOF之外的东西。

要获取文件大小,您可以fseek(file, 0, SEEK_END)然后调用ftell(file)

要逐字符读取字符,可以使用for (i = 0; fgetc(file) != EOF; i++);

我想知道程序是否曾经返回过,按照fseek()文档 feof()永远不会返回任何<>0

成功调用fseek()函数将清除流的文件结束指示符


要使用fseek()确定文件大小,请执行以下操作:

FILE * pf = ...;

fseek(pf, 0, SEEK_END);
long size = ftell(pf);

我最终做到了这一点,并且有效。

fseek(file, 0, SEEK_END);

然后调用ftell(file);

在我尝试这样做之前:

for (i = 0; fgetc(file) != EOF; i++);

它没有用...但是现在是0.0谢谢大家..!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM