#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <windows.h>
#define LEN 40
int main(int argc, char *argv[])
{
FILE * in,*out;
int ch;
char name[LEN];
int count = 0;
if(argc < 2)
{
fprintf(stderr,"Useage: %s filename",argv[0]);
exit(1);
}
if((in = fopen(argv[1],"r")) == NULL)
{
fprintf(stderr,"I could not open the file! \"%s\"\n",argv[1]);
exit(2);
}
strcpy(name,argv[1]);
strcat(name,".red");
if((out = fopen(name,"w")) == NULL)
{
fprintf(stderr,"can not create the output file!\n");
exit(3);
}
while((ch = getc(in)) != EOF)
{
if(count++ % 3 == 0)
putc(ch,out);
}
if(fclose(in) != 0 || fclose(out) != 0)
fprintf(stderr,"error in closing file!\n");
system("pause");
return 0;
}
今天在看C primer plus的时候看到了文件操作,于是,我想回顾下文件操作,不过遇到了点问题,最终解决了,也让我知道了很
多,分享下。
第一,对于main函数参数的理解,main函数很多时候大家都不会想到用参数,其实,他是有参数的。通常,他的参数有两个,int
main(int argc,char *argv[ ])或者是int main(int
argc , char ** argv),这里argv是一个数组,而argc是命令行参数个数,argv保存命令行参数首地址。main函数的实参是通过操作
系统的命令行得到的。
上面这段代码的作用就是打开一个文件,只保留没3个字符中的第3个来压缩文件,然后输出到以第一个文件后加.red结尾的文件
中。