2021.1.6 C语言之文件
- 文件有多种
- C语言中文件是一种数据组织方式,按照数据存放类型:字符流和二进制流分别称为文本文件和二进制文件
- 文件结构和自定义类型 typedef这个关键字可以把struct结构体重命名为FILE,来简化对复杂数据的定义
- 下面是一个将姓名密码输到文件夹的代码
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
struct sysueser{
char username[20];
char passward[8];
};
void encrypt (char *pwd);//定义加密函数
int main (void){
FILE*fp;
int i;
struct sysueser su;//结构体
if ((fp=fopen("f12-2.txt","w"))==NULL){//如果新建的文件夹找不到指针
printf ("FILE OPEN ERROR");
exit(0);//退出,类似于return 0 操作
}
for (i=1;i<=5;i++){//输入学生姓名,密码
printf("enter %d th sysuser(name passward):",i);
scanf("%s%s",su.username ,su.passward );
encrypt(su.passward );
fprintf (fp,"%s%s\n",su.username ,su.passward );
}
if(fclose(fp)){
printf("can’t close \n");
exit(0);
}
return 0;
}
void encrypt (char *pwd){
int i;
for(i=0;i<strlen(pwd);i++)
{
pwd[i]=pwd[i]^15;
}
}
老师写的类似改进版,多了一个 while !feof(fp)来控制
void main()
{
FILE *fp1,*fp2;
char ch;
if(( fp1 = fopen( "f2.txt", "r" )) == NULL){
printf(" File open error!\n" );
exit(0);
}
if(( fp2 = fopen( "f3.txt", "w" )) == NULL){
printf(" File open error!\n" );
exit(0);
}
while( !feof( fp1 ) )
{
ch = fgetc( fp1 );
if(ch!=EOF)
fputc(ch, fp2);
}
/*关闭文件f12-2.txt */
if(fclose(fp1))
{
printf("Can not close the file!\n");
exit(0);
}
/*关闭文件f12-3.txt */
if(fclose(fp2))
{
printf("Can not close the file!\n");
exit(0);
}
}
#endif