學c語言做練習之​統計文件中字符的個數


統計文件中字符的個數(采用命令行參數)

#include<stdio.h>
#include<stdlib.h>
int main(int argc, char *argv[])
{
 char ch;
 FILE *fp;
 long count=0;
 
 if(argc !=2)
 {
  printf("文件名是:%s\n",argv[0]);
  exit(EXIT_FAILURE);
 }
 if ((fp=fopen(argv[1],"r+"))==NULL)
 {
  fprintf(stderr,"不能打開文件\"%s\"\n",argv[1]);
  exit(EXIT_FAILURE);
 }
 while((ch=getc(fp)) !=EOF)
 {
  putc(ch,stdout);
  ++count;
 }
 fclose(fp);
 printf("File %s has %ld characters\n",argv[1],count);
 return 0;
}

 

統計文件中字符個數(不采用命令行參數)

#include<stdio.h>
#include<stdlib.h>
#define MAX 80
int main(void)
{
 FILE *fp;
 char ch;
 char name[MAX];
 long count=0;
 
 printf("請輸入文件名:");
 gets(name);
 if ((fp=fopen(name,"r+"))==NULL)
 {
  fprintf(stderr,"不能打開文件%s\n",name);
  exit(EXIT_FAILURE);
 }
 while((ch=getc(fp))!=EOF)
 {
  putc(ch,stdout);
  count++;
 }
 fclose(fp);
 printf("File %s has %ld characters\n",name,count);
 return 0;
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM