#include <stdio.h>
#include <stdbool.h>
// "1.txt" 桌面文件
void fileRead()
{
// 只读打开文件
FILE* fp=fopen("1.txt","r");
if(!fp)
{
perror("open file");
return;
}
// else printf("sucess!");
//读取文件
while(true){
char c=fgetc(fp);
if(feof(fp)) break;//文件的结束函数
// if(c==EOF) break;
printf("%c ",c);
}
fclose(fp);
}
void fileWrite()
{
//文件只写
FILE* fp=fopen("1.txt","w");
if(!fp)
{
perror("open fail");
return;
}
//写文件
char s[]="中话,";
for(int i=0;s[i];i++)
{
char c=fputc(s[i],fp);
printf("%c",c);
}
fclose(fp);
}
void fileReadWrite()
{
//文件可读可写
FILE* fp=fopen("1.txt","w+");
if(!fp)
{
perror("open fail");
return;
}
//写文件
int i=fputs("中华",fp);
printf("%d\n",i);
//把文件位置指针移动到文件开头
rewind(fp);
//读取文件
char c[128]={0};
char *ch=fgets(c,sizeof(c),fp);
printf("ch:%s c:%s",ch,c);
fclose(fp);
}
//格式化读取文件
void fileFormatRead()
{
FILE* fp=fopen("1.txt","r");
if(!fp){
perror("open fail");
return;
}
//格式化读取
char c[20]={0};
while(!feof(fp))
{
fscanf(fp,"%s",c);//将读取到的数据方到c数组中
printf("%s\n",c);
}
fclose(fp);
}
//格式化写入文件
void fileFormatWrite()
{
FILE* fp=fopen("1.txt","w");
if(!fp){
perror("open fail");
return;
}
//格式化写入
char c[]="尼曼\n滑落a";
int i=fprintf(fp,c);
printf("%d",i); // 10 :一个汉字2个字节
fclose(fp);
}
//文件拷贝
void fileCopy(const char *destfilename,const char *srcfilename)
{
FILE* fpw=fopen(destfilename,"w");
FILE* fpr=fopen(srcfilename,"r");
if(!fpr)
{
perror("open file");
return;
}
if(!fpw)
{
perror("open file");
return;
}
//缓冲区
char *buf=(char *)malloc(sizeof(char)*100);
int cnt=0;
//从输入缓冲区中读取100个字符到 buf数组中
while(fgets(buf,100,fpr)){
//将缓冲区中的字符写到fpw文件中
fputs(buf,fpw);
cnt++;
}
free(buf);
fclose(fpw);
fclose(fpr);
// cnt;
}
int main()
{
// fileRead();
// fileWrite();
// fileReadWrite();
// fileFormatRead();
// fileFormatWrite();
fileCopy("2.txt","1.txt");
return 0;
}