/* 带缓存的I/O 操作 */
/* fopen.c */
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp;
fp = fopen("hello.txt","w");
if(NULL == fp)
{
perror("fopen");
exit(1);
}
else
{
printf("Open the hello.txt success!\n");
}
fclose(fp);
return 0;
}
/* fread.c */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
FILE *fp;
char buf[3] = {0};
fp = fopen("hello.txt","r");
if(NULL == fp)
{
perror("fopen");
exit(1);
}
printf("Read from the txt:\n");
while(fread(buf,1,2,fp))
{
printf("%s",buf);
memset(buf,0,sizeof(buf));
}
fclose(fp);
return 0;
}
/* fwrite.c */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc,char **argv)
{
FILE *fp;
char buf[20] = {0};
if(argc < 2)
{
printf("Please input the pathname!\n");
exit(1);
}
fp = fopen(argv[1],"w");
if(NULL == fp)
{
perror("fopen");
exit(2);
}
while(1)
{
printf("Please input the string:\n");
scanf("%s",buf);
if(strcmp(buf,"end") != 0) //end 结束输入
{
fwrite(buf,1,32,fp);
memset(buf,0,sizeof(buf));
}
else
{
break;
}
}
fclose(fp);
return 0;
}
/* 带缓存的I/O的综合应用案例 copy.c */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc,char **argv)
{
FILE *fp1,*fp2;
char buf[64] = {0};
/* 参数判断 */
if(argc < 3)
{
printf("Input error!\n");
exit(1);
}
/* 打开两个文件 */
fp1 = fopen(argv[1],"r");
if(NULL == fp1)
{
perror("fopen1");
exit(2);
}
fp2 = fopen(argv[2],"w");
if(NULL == fp1)
{
perror("fopen2");
exit(3);
}
/* 打开被复制文件 写到复制文件 */
printf("Copying...\n");
while(fread(buf,1,32,fp1))
{
fwrite(buf,1,32,fp2);
memset(buf,0,sizeof(buf)); //每次进行一次清空,防止复制的内容里面出现奇怪的字符
}
printf("Coping success!\n");
/* 关闭文件 */
fclose(fp1);
fclose(fp2);
return 0;
}