作业一、
有一个usr.txt的文件,其中存储着用户的账户和密码,格式如下:
zhangsan aaaa
lisi bbbbb
空格前面是账户,空格后面是密码,一行一个账户、密码
要求如下:
从终端获取一个账户名和密码
判断是否能够登录成功
若账户不存在:则提示账户不存在
若账户存在,密码不匹配:则提示密码错误
账户密码均存在:则显示登录成功
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, const char *argv[])
{
char name[20], pw[20];
char my_name[20] = "", my_pw[20] = "";
FILE *fp = fopen("./usr.txt", "r");
if (NULL == fp)
{
perror("fp");
return -1;
}
printf("fopen succse\n");
printf("请输入用户名:");
scanf("%s", my_name);
printf("请输入用户密码:");
scanf("%s", my_pw);
while (1)
{
if (fscanf(fp, "%s %s", name, pw) == EOF)
{
printf("没有查询到该账户\n");
return -1;
}
if (strcmp(my_name, name) == 0 && strcmp(my_pw, pw) != 0)
{
printf("密码错误\n");
return 0;
}
if (strcmp(my_name, name) == 0 && strcmp(my_pw, pw) == 0)
{
printf("登录成功\n");
return 0;
}
bzero(name, sizeof(name));
bzero(pw, sizeof(pw));
}
if (EOF == fclose(fp))
{
perror("fp");
return -1;
}
printf("fclose succse");
return 0;
}
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct DATE
{
char name[20];
char pw[20];
} Date;
int main(int argc, const char *argv[])
{
Date date[2];
FILE *fp = fopen("./usr.txt", "r");
if (NULL == fp)
{
perror("fp");
return -1;
}
for (int i = 0; i < 2; i++)
{
fscanf(fp, "%s %s", date[i].name, date[i].pw);
}
char my_name[20] = "", my_pw[20] = "";
printf("请输入用户名:");
scanf("%s", my_name);
printf("请输入用户密码:");
scanf("%s", my_pw);
for (int i = 0; i < 2; i++)
{
if (strcmp(my_name, date[i].name) == 0)
{
if (strcmp(my_pw, date[i].pw) == 0)
{
printf("登录成功\n");
fclose(fp);
return 0;
}
printf("密码错误\n");
fclose(fp);
return 0;
}
}
printf("账号不存在\n");
fclose(fp);
return 0;
}
作业二、
要求拷贝一个文件,例如将1.c中的内容拷贝到2.c中
要求计算一个文件的大小。
要求计算一个文件有几行。文件的最后一行也有一个'\n'
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, const char *argv[])
{
char c;
int count=0,count1=0;
FILE *fp1 = fopen("./1.txt", "r");
FILE *fp2 = fopen("./2.txt", "w");
if (NULL == fp1)
{
perror("fp1");
return -1;
}
if (NULL == fp2)
{
perror("fp2");
return -1;
}
while(1)
{
c = fgetc(fp1);
if(c<0)
{
break;
}
else
{
//计算字符个数
fputc(c,fp2);
count++;
}
//计算行数
if(c =='\n')
count1++;
}
printf("2.txt的文件大小是%d\n",count);
printf("2.txt的文件的换行是%d\n",count1);
fclose(fp1);
fclose(fp2);
return 0;
}