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. "); else { int i = 0; while((ch = fgetc(fp)) != EOF) { if(ch != ' ') i++; } fclose(fp); printf("There %d characters in this file. ", 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. "); else { int i = 0; while(fscanf(fp, "%s", ch) == 1) i++; fclose(fp); printf("There are %d fields in this file. ", i); } return 0; }