1.代码
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, const char *argv[])
{
FILE *fs = fopen("usr.txt", "a+");
if (NULL == fs)
{
printf("__%d__\n", __LINE__);
perror("fopen");
return -1;
}
//char txt_user[20][20];
//char txt_psw[20][20];
char txt_user[20] = "";
char txt_psw[20] = "";
char ter_user[20] = "";
char ter_psw[20] = "";
int i = 0;
int res = 0;
printf("请输入账号:\n");
scanf("%s", ter_user);
//getchar();
printf("请输入密码:\n");
scanf("%s", ter_psw);
while(1)
{
//fscanf(fs, "%s", txt_user);
res = fscanf(fs, "%s %s", txt_user, txt_psw);
if (EOF == res)
{
printf("账号不存在\n");
break;
}
if (strcmp(ter_user, txt_user) == 0)
{
if (strcmp(ter_psw, txt_psw) == 0)
{
printf("登录成功\n");
break;
}
else
{
printf("密码错误\n");
break;
}
}
}
fclose(fs);
fs = NULL;
if (res == -1)
{
//printf("账户不存在, 系统自动注册,请重新登录\n");
FILE *fp = fopen("usr.txt", "a");
if (NULL == fp)
{
printf("__%d__\n", __LINE__);
perror("fopen");
return -1;
}
fprintf(fp, "%s ", ter_user);
fprintf(fp, "%s\n", ter_psw);
printf("注册新账号成功\n");
fclose(fp);
fp = NULL;
}
return 0;
}
结果
2.代码
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, const char *argv[])
{
FILE *fp_r = fopen("2.c", "r+");
if (NULL == fp_r)
{
perror("fopen");
return -1;
}
FILE *fp_w = fopen("2.txt", "w");
if (NULL == fp_w)
{
perror("fopen");
return -1;
}
int count = 0, line = 0;
char c;
while ((c = fgetc(fp_r)) != EOF)
{
count++;
if(c == '\n')
line++;
fputc(c, fp_w);
}
printf("字符个数为%d 文件行数为%d\n", count, line);
fclose(fp_r);
fclose(fp_w);
fp_r = NULL;
fp_w = NULL;
fp_w = fopen("2.txt", "r");
printf("以下为2.txt的内容:\n");
while ((c = fgetc(fp_w)) != EOF)
{
printf("%c", c);
}
fclose(fp_w);
fp_w = NULL;
return 0;
}
结果
思维导图