嵌入式Linux标准IO,拷贝文件fgetc()/fputc(),fread()/fwrite()
2019-07-13 06:40发布
生成海报
文章目录
1,按字符输入fgetc(),getc(),getchar()
下列函数用来输入一个字符:
#include
int fgetc(FILE *stream);
int getc(FILE *stream);
int getchar(void);
- 成功时返回读取的字符; 若到文件末尾或出错时返回EOF
- getchar()等同于fgetc(stdin)
2,按字符输出fputc(),putc(),putchar()
下列函数用来输出一个字符:
#include
int fputc(int c, FILE *stream);
int putc(int c, FILE *stream);
int putchar(int c);
- 成功时返回写入的字符; 出错时返回EOF
- putchar©等同于fputc(c, stdout)
3,通过fgetc()/fputc()拷贝文件
#include
#include
#include
int get_file_size(const char *file);
int my_write_file_char(const char *file,const char *mode,char ch);
int my_cp_file(const char *src_file,const char *dst_file,const char *mode);
int main(int argc, const char *argv[])
{
int ch;
if(argc <3)
{
printf("usage:%s
",argv[0]);
return -1;
}
printf("src_total %d bytes
",get_file_size(argv[1]));
ch = fgetc(stdin);
my_write_file_char(argv[1],"w",ch);
printf("src_total %d bytes
",get_file_size(argv[1]));
ch ='a';
while(ch <= 'z')
{
my_write_file_char(argv[1],"a+",ch);
ch++;
}
printf("src_total %d bytes
",get_file_size(argv[1]));
printf("dst_total %d bytes
",get_file_size(argv[2]));
my_cp_file(argv[1],argv[2],"w");
printf("dst_total %d bytes
",get_file_size(argv[2]));
return 0;
}
int get_file_size(const char *file)
{
int count=0;
FILE *fp;
if((fp = fopen(file,"r")) == NULL)
{
perror("get_size_fopen");
return -1;
}
while(fgetc(fp) != EOF)
{
count ++;
}
if(fclose(fp) == EOF)
{
perror("_get_size_fclose");
return EOF;
}
return count;
}
int my_write_file_char(const char *file,const char *mode,char ch)
{
FILE *fp;
if((fp = fopen(file,mode)) == NULL)
{
perror("write_file_char_fopen");
return -1;
}
fputc(ch,fp);
if(fclose(fp) == EOF)
{
perror("fclose");
return EOF;
}
}
int my_cp_file(const char *src_file,const char *dst_file,const char *mode)
{
char ch;
FILE *src_fp,*dst_fp;
if((src_fp = fopen(src_file,"r")) == NULL)
{
perror("src_fopen");
return -1;
}
if((dst_fp = fopen(dst_file,mode)) == NULL)
{
perror("dst_fopen");
return -1;
}
while((ch = fgetc(src_fp)) != EOF)
{
fputc(ch,dst_fp);
}
if(fclose(src_fp) == EOF)
{
perror("src_fclose");
return EOF;
}
if(fclose(dst_fp) == EOF)
{
perror("dst_fclose");
return EOF;
}
}
运行结果
通过fread()/fwrite()拷贝文件
int my_cp_file(const char *src_file,const char *dst_file,const char *mode)
{
const int N = 64;
char buf[N];
int n = 0;
FILE *src_fp,*dst_fp;
if((src_fp = fopen(src_file,"r")) == NULL)
{
perror("src_fopen");
return -1;
}
if((dst_fp = fopen(dst_file,mode)) == NULL)
{
perror("dst_fopen");
return -1;
}
while((n = fread(buf,1,N,src_fp)) > 0)
{
fwrite(buf,1,n,dst_fp);
}
if(fclose(src_fp) == EOF)
{
perror("src_fclose");
return EOF;
}
if(fclose(dst_fp) == EOF)
{
perror("dst_fclose");
return EOF;
}
}
运行结果
打开微信“扫一扫”,打开网页后点击屏幕右上角分享按钮