1.用fgetc与fputc函数实现:运算符优先级: =号优先级最低。
文件拷贝,例如将1.txt的内容拷贝到2.txt中
要求用fgetc计算一个文件有多少个字节
用fgetc计算一个文件有几行? 计算\n个数字
#include <stdio.h>
#include <errno.h>
int main()
{
char c;
int hang = 0;;
int count1 = 0;
int ch;
FILE *fp;
fp = fopen("txt1.c","r");
if(NULL == fp)
{
perror("fopen");
return -1;
}
printf("只读形式打开文件成功!\n");
FILE *fp1;
fp1 = fopen("txt2.c","w+");
if(NULL == fp1)
{
perror("fopen");
return -1;
}
printf("只写形式打开文件成功!\n");
while(1)
{
ch = fgetc(fp);
if(ch == '\n')
{
hang++;
}
if(EOF == ch)
break;
count1++;
fputc(ch,fp1);
// printf("%c",ch);
}
printf("hang = %d\n",hang);
printf("fp1 = %d\n",count1);
fclose(fp);
fclose(fp1);
return 0;
}
只读形式打开文件成功!
只写形式打开文件成功!
hang = 5
fp1 = 22
2.实现登录功能。自定义一个usr.txt,手动输入账户密码,格式如下:账户 密码
需求如下:
1.从终端获取账户密码,与文件中的账户密码比较
2.若终端输入的账户不存在,则输出账户不存在
3.若终端输入的账户存在,但是密码不正确,则输出密码错误
4.若账户密码均正确,则输出登录成功
附加题
5.实现注册功能,注册的账户密码存储在上一题的文件中。需求:不能重复注册
#include <stdio.h>
#include <errno.h>
#include <string.h>
int main()
{
int ch;
FILE *fp;
char id[20];
fp = fopen("usr.txt","a+");
if(NULL == fp)
{
perror("fopen");
return -1;
}
//printf("打开成功!");
char r;
lk:
printf("----ID Sign in-----(Y/N)?\n");
scanf(" %c",&r);
if(r == 'y' || r == 'Y')
{
char zhanghu[20];
char mima[20];
printf("please enter ID : ");
scanf("%s",zhanghu);
printf("please enter Password : ");
scanf("%s",mima);
int k1;
while(1)
{
//ID重命名判定
k1 = fscanf(fp,"%s",id);
if(EOF == k1)
{
// printf("ID不重复!\n");
fprintf(fp,"%s %s",zhanghu,mima);
fprintf(fp,"%c",'\n');
printf("注册ID成功!\n");
break;
}
if(strcmp(id,zhanghu) == 0 )
{
printf("用户ID重复,请重新输入!\n");
goto lk;
}
fscanf(fp,"%s",id);
}
}
fclose(fp);
printf("------ID Log in--------\n");
fp = fopen("usr.txt","r");
if(NULL == fp)
{
perror("fopen");
return -1;
}
char zh[20];
char mm[20];
printf("ID : ");
scanf("%s",zh);
printf("password : ");
scanf("%s",mm);
int k;
while(1)
{
//ID判定
k = fscanf(fp,"%s",id);
if(EOF == k)
{
printf("ID不存在!\n");
break;
}
if(strcmp(id,zh) != 0 )
{
fscanf(fp,"%s",id);
continue;
}
//password
fscanf(fp,"%s",id);
if(strcmp(id,mm) != 0)
{
printf("Password error!\n");
break;
}
printf("Log in success!\n");
break;
}
fclose(fp);
return 0;
}
----ID Sign in-----(Y/N)?
y
please enter ID : 123
please enter Password : 123
用户ID重复,请重新输入!
----ID Sign in-----(Y/N)?
n
------ID Log in--------
ID : tjq
password : 123456
Log in success!
3.Xmaid