1. 程式人生 > >C primer plus 程式設計練習 13.11

C primer plus 程式設計練習 13.11

//cpp 13.11-1
#include <stdio.h>
#include <stdlib.h>
#define LEN 41

int main(void)
{
	int ch;
	FILE *fp;
	char file[LEN];
	int count = 0;

	puts("請輸入您要開啟的檔名:");
	scanf("%40s",file);
	if ((fp = fopen(file,"r")) == NULL)
	{
		printf("無法開啟%s\n",file);
		exit(EXIT_FAILURE);
	}
	while ((ch = getc(fp)) != EOF)
	{
		putc(ch,stdout);
		count++;
	}
	fclose(fp);
	printf("檔案 %s 含有 %d 個字元\n",file,count);

	return 0;
}
//CPP 13.11-3
#include <stdlib.h>
#include <ctype.h>
#define LEN 41

int main()
{
    int ch; //讀取檔案時儲存每個字元的地方
    FILE * fp1;
	FILE * fp2;
	char file[LEN];
    puts("請輸入您要開啟的檔名:");
	scanf("%40s",file);
	if ((fp1 = fopen(file,"r")) == NULL)
	{
		printf("無法開啟%s\n",file);
		exit(EXIT_FAILURE);
	}
	if ((fp2 = fopen(file,"a")) == NULL)
	{
		printf("無法開啟%s\n",file);
		exit(EXIT_FAILURE);
	}
	while ((ch = getc(fp1)) != EOF)
	{
		ch = toupper(ch);
		putc(ch,fp2);
	}
    if (fclose(fp1) != 0)
        printf("Could not close file %s\n", file);
	if (fclose(fp2) != 0)
        printf("Could not close file %s\n", file);
    return 0;
}
//CPP 13.11-6
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define LEN 80

int main(void)
{
	FILE *in,*out;
	int ch;
	char nameout[LEN];
    char namein[LEN];
	int count = 0;
    //開啟原始檔,設定輸入
	puts("請輸入您要開啟的檔名:");
	scanf("%s",namein);
	if ((in = fopen(namein,"r")) == NULL)
	{
		printf("無法開啟%s\n",namein);
		exit(EXIT_FAILURE);
	}
    //設定輸出
    strncpy(nameout,namein,LEN - 5); //拷貝檔名
    nameout[LEN - 5] = '\0';
	strcat(nameout,".red");
	if ((out = fopen(nameout,"w")) == NULL)
	{
		fprintf(stderr,"無法開啟建立的輸出檔案\n");
		exit(3);
	}
	//拷貝資料
	while ((ch = getc(in)) != EOF)
	{
		if (count++ % 3 == 0)
		    putc(ch,out);      //只輸出三個字元中的第一個
	}
	if (fclose(in) != 0 || fclose(out) != 0)
	{
		fprintf(stderr,"關閉檔案時失敗");
	}
	return 0;
}
//CPP 13.11-8
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define LEN 80

int main(int argc,char *argv [])
{
	FILE *fp;
	char ch;   //待統計的字元
	char chf;
	int count = 0;   //統計計數
	char input[100];
	if (argc <= 2)
	{   
		if (argc == 1)
		{
		    printf("您沒輸入待統計的字元,請輸入\n");
	        scanf("%c",&ch);
		}
		printf("您沒有輸入待統計的檔名,請輸入一段待統計的字元\n");
		scanf("%100s",input);
		puts(input);
		int i = 0;
		while ((chf = input[i]) != '\0' )
	    {
			if (ch == chf)
			    count++;
			i++;
	    }
		printf("您輸入的字串中含有 %d 個 %c 字元\n",count,ch);
	}
	else
	{
		if ((fp = fopen(argv[2],"r")) == NULL)
		{
            fprintf(stderr,"無法開啟%s\n",argv[2]);
		    exit(EXIT_FAILURE);
		}
		ch = argv[1][0];
		while ((chf = getc(fp)) != EOF)
	    {
			if (ch == chf)
			    count++;
	    }
		printf("檔案 %s 中含有 %d 個 %c 字元\n",argv[2],count,ch);
	    if (fclose(fp) != 0)
		    fprintf(stderr,"關閉檔案時失敗");
	}
	return 0;
}