1.用fgetc计算一个文件的大小,要求封装成函数
#include <stdio.h>
int bety(FILE *fp)
{
if(NULL == fp)
{
perror("fopen");
return -1;
}
int count = 0;
while(fgetc(fp)!=-1)
{
count++;
}
return count;
}
int main(int argc, const char *argv[])
{
if(argc < 2)
{
printf("请输入文件名\n");
return -1;
}
FILE *fp = fopen(argv[1],"r");
if(NULL == fp)
{
perror("fopen");
return -1;
}
printf("文件大小是%d字节\n",bety(fp));
fclose(fp);
return 0;
}
2.用fgetc计算一个文件有几行,要求封装成函数(linux操作系统以\n结尾,就算是最后一行也有一个'\n')
#include <stdio.h>
int line(FILE *fp)
{
if(NULL == fp)
{
perror("fopen");
return -1;
}
int count = 0;
char c;
while((c=fgetc(fp))!=-1)
{
if(c=='\n')
{
count++;
}
}
return count;
}
int main(int argc, const char *argv[])
{
if(argc < 2)
{
printf("请输入文件名\n");
return -1;
}
FILE *fp = fopen(argv[1],"r");
if(NULL == fp)
{
perror("fopen");
return -1;
}
printf("文件有%d行\n",line(fp));
fclose(fp);
return 0;
}
3.用fgets和fputs实现,拷贝一个文件,例如将1.c的内容拷贝给2.c
#include <stdio.h>
int copy_file(FILE *fp1,FILE *fp2)
{
if(NULL==fp1 || NULL==fp2)
{
perror("fopen");
return -1;
}
char arr[20];
while(fgets(arr,sizeof(arr),fp1) != NULL)
{
fputs(arr,fp2);
}
printf("复制完成\n");
return 0;
}
int main(int argc, const char *argv[])
{
if(argc < 3)
{
printf("请输入文件名\n");
return -1;
}
FILE *fp1 = fopen(argv[1],"r");
FILE *fp2 = fopen(argv[2],"w");
if(NULL==fp1 || NULL==fp2)
{
perror("fopen");
return -1;
}
copy_file(fp1,fp2);
fclose(fp1);
fclose(fp2);
return 0;
}
4.用fgets计算一个文件的大小,要求封装成函数
#include <stdio.h>
int byte(FILE *fp)
{
if(NULL==fp)
{
perror("fopen");
return -1;
}
char arr[2];
int count = 0;
while(fgets(arr,2,fp) != NULL)
{
count++;
}
return count;
}
int main(int argc, const char *argv[])
{
if(argc < 2)
{
printf("请输入文件名\n");
return -1;
}
FILE *fp = fopen(argv[1],"r");
if(NULL==fp)
{
perror("fopen");
return -1;
}
printf("文件占%d个字节\n",byte(fp));
fclose(fp);
return 0;
}
5.用fgets计算一个文件有几行,要求封装成函数(linux操作系统以\n结尾,就算是最后一行也有一个'\n')
#include <stdio.h>
int line(FILE *fp)
{
if(NULL==fp)
{
perror("fopen");
return -1;
}
char arr[2];
int count = 0;
while(fgets(arr,2,fp) != NULL)
{
if(arr[0]=='\n')
{
count++;
}
}
return count;
}
int main(int argc, const char *argv[])
{
if(argc < 2)
{
printf("请输入文件名\n");
return -1;
}
FILE *fp = fopen(argv[1],"r");
if(NULL==fp)
{
perror("fopen");
return -1;
}
printf("文件占有%d行\n",line(fp));
fclose(fp);
return 0;
}