1
实现登录功能。自定义一个usr.txt,手动输入账户密码,格式如下:账户 密码
例如: zhangsan 12345
lisi abcde
wangwu abc123
需求如下:
从终端获取账户密码,与文件中的账户密码比较
若终端输入的账户不存在,则输出账户不存在
若终端输入的账户存在,但是密码不正确,则输出密码错误
若账户密码均正确,则输出登录成功
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, const char *argv[])
{
FILE *fp = fopen("user.txt","a+");
if(NULL == fp)
{
perror("fopen");
return -1;
}
printf("open success\n");
char name[20] = "";
char passwd[20] = "";
printf("请输入账号和密码:");
scanf("%s%s",name,passwd);
char name_txt[20] = "";
char passwd_txt[20] = "";
int c=0;
while(strcmp(name,name_txt) != 0)
{
c = fscanf(fp,"%s%s",name_txt,passwd_txt);
if(c == EOF)
break;
printf("1\n");
}
if(0 == strcmp(name,name_txt) && 0 == strcmp(passwd,passwd_txt))
{
printf("登录成功\n");
}
else if(0 == strcmp(name,name_txt) && 0 != strcmp(passwd,passwd_txt))
{
printf("密码错误\n");
}
else
printf("账号不存在\n");
if(fclose<0)
{
perror("fclose");
return -1;
}
printf("close success\n");
return 0;
}
2
用fgetc与fputc函数实现:
1)文件拷贝,例如将1.txt的内容拷贝到2.txt中
2)要求用fgetc计算一个文件有多少个字节
3)用fgetc计算一个文件有几行?
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, const char *argv[])
{
FILE *fp_r = fopen("1.txt","r");
FILE *fp_w = fopen("./2.txt","w");
if(NULL == fp_r)
{
printf("__%d__\n",__LINE__);
perror("fopen");
return -1;
}if(NULL == fp_w)
{
printf("__%d__\n",__LINE__);
perror("fopen");
return -1;
}
char c;
int count=0,line=0;
while((c = fgetc(fp_r)) != EOF)
{
count++;
if(c == '\n')
line++;
fputc(c,fp_w);
}
printf("文件字节数为%d\n,行数为%d\n",count,line);
if(fclose(fp_r) < 0)
{
printf("__%d__\n",__LINE__);
perror("fclose");
return -1;
}
if(fclose(fp_w) < 0)
{
printf("__%d__\n",__LINE__);
perror("fclose");
return -1;
}
return 0;
}
XMIND