1、实现登录功能。自定义一个usr.txt,手动输入账户密码,格式如下:账户密码
例如:zhangsan 12345
lisi abcde
wangwu abc123
需求如下:
a.从终端获取账户密码,与文件中的账户密码比较b.若终端输入的账户不存在,则输出账户不存在
c.若终端输入的账户存在,但是密码不正确,则输出密码错误d.若账户密码均正确,则输出登录成功
#include <stdio.h>
#include <errno.h>
#include <string.h>
int main(int argc, char const *argv[])
{
FILE *fp = fopen("./usr.txt", "a+");
if(NULL == fp)
{
perror("fp");
return -1;
}
char str1[32] = "", str2[32] = "", str3[32], str4[32] = "";
printf("账号:");
scanf("%s", str1);
printf("密码:");
scanf("%s", str2);
int res = 0, temp = 0, a = 0;
while(res != EOF)
{
res = fscanf(fp, "%s %s", str3, str4);
if(EOF == res)
break;
a++;
if(strcmp(str2, str4) == 0 && strcmp(str1, str3) == 0)
{
printf("登陆成功\n");
break;
}
else if(strcmp(str1, str3) == 0 && strcmp(str2, str4) != 0)
{
printf("密码错误\n");
break;
}
else
temp++;
}
if(a == temp)
printf("账户不存在\n");
if(fclose(fp) != 0)
{
perror("fp");
return -1;
}
return 0;
}
2、计算一个文件的大小,请封装成函数。
//计算文件大小函数
#include <stdio.h>
long size(FILE *fp)
{
long len = 0;
char c;
while(1)
{
c = fgetc(fp);
if(EOF == c)
break;
len++;
}
return len;
}
int main(int argc, char const *argv[])
{
FILE *fp = fopen("./usr.txt","r+");
printf("%ld\n",size(fp));
fclose(fp);
return 0;
}
3、用fgets和fputs实现文件拷贝
#include <stdio.h>
//将文件1拷贝到文件2
void sp(FILE *fp2, FILE *fp1)
{
char str[32] = "";
while(fgets(str, sizeof(str), fp1))
{
fputs(str, fp2);
}
return ;
}
int main(int argc, char const *argv[])
{
FILE *fp1 = fopen("./1.txt", "a+");
FILE *fp2 = fopen("./2.txt", "a+");
sp(fp2, fp1);
fclose(fp1);
fclose(fp2);
return 0;
}