第一题
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define LEN 81
char s_gets(char * st, int n);
int main()
{
printf("13.11.1:\n");
FILE *fp;
char file_a[LEN];
char ch;
int count=0;
printf("Enter the file name: ");
s_gets(file_a,LEN);
if((fp = fopen(file_a,"r")) == NULL){
printf(stderr, "Can't open %s\n.",file_a);
exit(EXIT_FAILURE);
}
while((ch = getc(fp))!= EOF){
putc(ch,stdout);
count++;
}
fclose(fp);
printf("\nFile %s has %lu characters\n", file_a,count);
return 0;
}
char s_gets(char * st, int n){
char * ret_val;
char * find;
ret_val = fgets(st, n, stdin);
if(ret_val){
find =strchr(st,'\n');
if(find){
*find='\0';
}
else{
while(getchar() !='\n'){
continue;
}
}
}
return ret_val;
}
第二题
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char*argv[])
{
printf("13.11.2\n");
FILE *p1,*p2;
int ch;
if(argc !=3){
printf("Usage: %s filename\n",argv[0]);
exit(EXIT_FAILURE);
}
if((p1=fopen(argv[1],"r"))==NULL){
printf("Can't open the file.");
exit(EXIT_FAILURE);
}
if((p2=fopen(argv[2],"w"))==NULL){
printf("Can't output the file.");
exit(EXIT_FAILURE);
}
while((ch=getc(p1))!= EOF){
putc(ch,p2);
}
if(fclose(p1)!=0 || fclose(p2)!=0){
printf("Error in close file.");
}
return 0;
}
第三题
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#define MAX 10000
#define LEN 81
char * s_gets(char * st,int n);
int main()
{
printf(“13.11.3:\n”);
FILE *fp,*f2;
char *tem=“tem.txt”;
char a[LEN];
printf("Enter the file name: ");
s_gets(a,LEN);
if((fp=fopen(a,“r+”))== NULL){
fprintf(stderr,“Can’t open the %s file”,a);
exit(EXIT_FAILURE);
}
if((f2=fopen(tem,“w+”))==NULL){
fprintf(stderr,“Can’t create file”);
exit(EXIT_FAILURE);
}
int ch;
while((ch=getc(fp))!=EOF){
putc(toupper(ch),f2);
}
rewind(f2);
rewind(fp);
while((ch=getc(f2))!=EOF){
putc(ch,fp);
}
if(fclose(fp)!=0 || fclose(f2) !=0){
fprintf(stderr,“Error in closing the file.”);
exit(EXIT_FAILURE);
}
remove(tem);
printf(“Done”);
return 0;
}
char * s_gets(char * st,int n){
char * ret_val;
char *find;
ret_val=fgets(st,n,stdin);
if(ret_val){
find=strrchr(st,’\n’);
if(find){
*find=’\0’;
}
else{
while(getchar()!=’\n’){
continue;
}
}
}
return ret_val;
}
第四题
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
printf("13.11.4\n");
FILE *fp;
char ch;
if(argc==1){
fprintf(stderr,"There is no file.");
exit(EXIT_FAILURE);
}
for(int i=1;i<argc;i++){
if((fp=fopen(argv[i],"r"))==NULL){
fprintf(stderr,"Can't open the %s file.",argv[i]);
exit(EXIT_FAILURE);
}
while((ch=getc(fp))!=EOF){
putc(ch,stdout);
}
if(fclose(fp)!=0){
fprintf(stderr,"Can't close the file.");
exit(EXIT_FAILURE);
}
}
printf("\nDone!");
return 0;
}
第五题
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[])
{
printf("13.11.5\n");
FILE *fp,*fp2;
char ch;
if(argc==1){
fprintf(stderr,"There is no file.");
exit(EXIT_FAILURE);
}
if((fp=fopen(argv[1],"a+"))==NULL){
fprintf(stderr,"Can't open the source file.");
exit(EXIT_FAILURE);