1、实现注册功能,不会重复注册
#include <stdio.h>
#include <string.h>
int main(int argc, const char *argv[])
{
FILE *fp = fopen("./sign.txt", "a+");
FILE *fp1 = fopen("./usr.txt", "a+");
if(NULL == fp || NULL == fp1)
{
perror("fopen");
return -1;
}
char Account[20];
char Passwd[20];
printf("请输入用户名:");
scanf("%s", Account);
printf("请输入密码:");
scanf("%s", Passwd);
fprintf(fp, "%s %s\n", Account, Passwd);
fseek(fp, 0, SEEK_SET);
char Account1[20], Passwd1[20];
while(1)
{
int information = fgetc(fp);
fputc(information, fp1);
if(information == EOF)
break;
}
fseek(fp1, 0, SEEK_SET);
while(1)
{
if(fscanf(fp1, "%s %s", Account1, Passwd1) == EOF)
{
printf("用户可以注册\n");
break;
}
if(strcmp(Account, Account1) == 0)
{
if(strcmp(Passwd, Passwd1) == 0)
{
printf("用户已经存在\n");
break;
}
else
printf("用户存在,密码错误\n");
}
}
if(fclose(fp) < 0)
{
perror("fclose");
return -1;
}
fclose(fp1);
return 0;
}
输出结果
请输入用户名:lisi
请输入密码:123
用户已经存在
请输入用户名:lisi
请输入密码:23425
用户存在,密码错误
用户可以注册
2、封装函数,获取文件的行数和字节数
#include <stdio.h>
void Getline(FILE *fp)
{
int count = 0;
int line = 0;
while(1)
{
line = fgetc(fp);
if(line == '\n')
count++;
if(line == EOF)
break;
}
printf("共有%d行\n", count);
}
void Getsize(FILE *fp)
{
int count = 0;
int word = 0;
while(1)
{
word = fgetc(fp);
if(word != EOF)
count++;
else
break;
}
printf("共有%d字节\n", count);
}
int main(int argc, const char *argv[])
{
FILE *fp = fopen("usr.txt", "r");
Getline(fp);
fseek(fp, 0, SEEK_SET);
Getsize(fp);
if(fclose < 0)
{
printf("关闭失败\n");
return -1;
}
return 0;
}
输出结果:
共有20行
共有645字节