1. 程式人生 > 其它 >一個簡單的檔案壓縮程式

一個簡單的檔案壓縮程式

技術標籤:基礎程式碼片段理解C primer plus書本中的理解內容指標

#include<stdio.h>
#include<stdbool.h>
#include<stdlib.h> //為 malloc()\free() 、exit()提供原型
#include<string.h>
#define LEN 100

int main(int argc, char *argv[])
{
	FILE *in, *out;
	int ch;
	char name[LEN]; //儲存輸入檔名
	int count = 0;

	//檢查命令列
	if (
argc < 2) { fprintf(stderr,"usage: %s filename.\n",argv[0]); //第一個引數必須是指標 //fprintf(fp, "%d, %6.2f", i, t)  將整型變數 i 和實型變數 t 的值按%d和%6.2f的格式輸出到fp所指向的檔案中 //這裡是使用【stderr指標】把錯誤訊息傳送至標準錯誤 exit(EXIT_FAILURE);//引數異常,終止 } //設定輸入 if ((in = fopen("1.txt", "r"
)) == NULL) { fprintf(stderr, "i couldn't open the file \"%s\" \n", "2.txt"); exit(EXIT_FAILURE);//引數異常,終止 } //設定輸出 strncpy(name, "2.txt", LEN - 5); //從txt中拷貝4個字元到數組裡 name[LEN - 5] = '\0'; //新增上字串結束標誌 :空字元 strcat(name, ".red"); //在檔名後面拼接上.red(追加)
if ((out = fopen(name, "w")) == NULL) { //寫模式開啟檔案 fprintf(stderr, "can't create output file.\n"); exit(3);//引數異常,傳遞非0值,終止 } //拷貝資料 while ((ch = getc(in)) != EOF) { //getc從檔案指標 in 指定的檔案中獲取一個字元 if (count++ % 3 == 0)//每隔3個取出一個字元 :(0 1 2 3)取出3 { putc(ch, out); } //將字元輸入輸出到檔案指標out 指定的檔案中 } //收尾 if (fclose(in) != 0 || fclose(out) != 0) { //關閉成功返回0,退出,否則 : fprintf(stderr, "關閉檔案錯誤。\n"); } exit(0); }