// p.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include<stdio.h>
#include<string.h>
int n_char(FILE *fp)
{ int num = 0;
char s[20];
while(!feof(fp))
{ fscanf(fp, "%s", s); //讀取字元串 num += strlen(s); //疊加字元數
}
printf("字元數(不計空格和回車)有%d個\n",num);
rewind(fp); //繞回檔案指針
return num;
}
int n_world(FILE *fp)
{
char s[20];
int n = 0, num = 0;
while(!feof(fp))
{
if(fscanf(fp, "%s", s) && !(s[0] >='0' && s[0] <='9'))
n++;
else
num++;
}
printf("單詞數有%d個,數字有%d個\n",n,num);
rewind(fp);
return n;
int n_row(FILE *fp)
{
int n = 1;
char ch;
while(!feof(fp))
{
if((ch = fgetc(fp) == '\n')) n++;
printf("有%d行\n", n); rewind(fp);
return n;
void main()
FILE *fp;
fp = fopen("d:\\aaa.txt", "r"); //打開檔案
n_char(fp);
n_world(fp);
n_row(fp);
fclose(fp);
}
運作測試