1. file copying implemented using fscanf and fprintf
#include <stdio.h>
#include <string.h>
int main(int argc, char const *argv[])
{
//打开fopen, r
FILE *fp = fopen("./01_fopen.c","r");
if(NULL == fp)
{
perror("fopen");
return -1;
}
printf("fopen succeed\n");
char file_name[20];
printf("输入您要拷贝到的文件的文件名:");
scanf("%s",file_name);
FILE *fp1 = fopen(file_name,"w");
if(NULL == fp1)
{
perror("fopen");
return -1;
}
printf("%s open succeed\n",file_name);
/*************code logic begin****************/
char c = 0;
while (fscanf(fp,"%c",&c)>0)
{
fprintf(fp1,"%c",c);
memset(&c,0,sizeof(c));
}
/*************code logic end****************/
if(fclose(fp) < 0)
{
perror("fclose");
return -1;
}
printf("fp fclose succeed\n");
if(fclose(fp1) < 0)
{
perror("fclose");
return -1;
}
printf("fp1 fclose succeed\n");
return 0;
}
2. calculating file lines using fgetc
#include <stdio.h>
#define ERR_MSG(msg) do{\
printf("line:%d\n",__LINE__);\
perror(msg);\
}while (0);
void calculate_file_lines(const char* filename)
{
int file_line = 0;
//打开fopen, r
//FILE *fp = fopen("./01_fopen.c","r");
FILE *fp = fopen(filename,"r");
if(NULL == fp)
{
ERR_MSG(filename);
return;
}
printf("%s open succeed\n",filename);
/*************code logic begin****************/
char c = 0;
while (1)
{
c = fgetc(fp);
if (EOF==c)
{
break;
}
if ('\n' == c)
{
file_line++;
}
}
//printf("the lines of 01_fopen.c is %d\n",file_line);
printf("the lines of %s is %d\n",filename,file_line);
/*************code logic end****************/
if(fclose(fp) < 0)
{
perror("fclose");
return;
}
printf("fp fclose succeed\n");
}
int main(int argc, char const *argv[])
{
if (argc <= 1)
{
printf("请输入文件名,usage:%s filename\n",argv[0]);
return -1;
}
calculate_file_lines(argv[1]);
return 0;
}
3.calculating file size using fgetc
#include <stdio.h>
#define ERR_MSG(msg) do{\
printf("line:%d\n",__LINE__);\
perror(msg);\
}while (0);
void calculate_file_size(const char *filename)
{
int file_size = 0;
//打开fopen, r
FILE *fp = fopen(filename,"r");
if(NULL == fp)
{
ERR_MSG(filename);
return;
}
printf("%s open succeed\n",filename);
/*************code logic begin****************/
char c = 0;
while (1)
{
c = fgetc(fp);
if (EOF==c)
{
break;
}
file_size++;
}
printf("the size of %s is %d bytes\n",filename,file_size);
/*************code logic end****************/
if(fclose(fp) < 0)
{
perror("fclose");
return;
}
printf("fp fclose succeed\n");
}
int main(int argc, char const *argv[])
{
if (argc <= 1)
{
printf("请输入文件名,usage:%s filename\n",argv[0]);
return -1;
}
calculate_file_size(argv[1]);
return 0;
}