微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c语言 13-7 利用fgetc函数输出文件的字符数

1、

#include <stdio.h>

int main(void)
{
    FILE *fp;
    int ch;
    char filename[FILENAME_MAX];
    printf("Please input the filename: "); scanf("%s", filename);
    
    if((fp = fopen(filename, "r")) == NULL)
        printf("\aFile open Failed.\n");
    else
    {
        int i = 0;
        while((ch = fgetc(fp)) != EOF)
        {
            if(ch != '\n')
                i++;    
        }
        fclose(fp);
        printf("There %d characters in this file.\n", i);
    }
    return 0;
} 

 

 

 

 

2、利用fscanf统计字段数

#include <stdio.h>

int main(void)
{
    FILE *fp;
    char ch[128];
    char filename[FILENAME_MAX];
    printf("Please input the filename: "); scanf("%s", filename);
    
    if((fp = fopen(filename, "r")) == NULL)
        printf("\aFile open Failed.\n");
    else
    {
        int i = 0;
        while(fscanf(fp, "%s", ch) == 1)
            i++;
        fclose(fp);
        printf("There are %d fields in this file.\n", i);
    }
    return 0;
}

 

 

 

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐