作业:
1>
要求:
源代码:
#include "myhead.h"
int main(int argc, char const *argv[])
{
FILE *fp=NULL;
if ((fp=fopen("./text.txt","r"))==NULL)
{
perror("fopen error");
return -1;
}
char buf[64]={0};
int line=0;
while((fgets(buf, sizeof(buf)-1, fp)) != NULL)//循环读取fp中的内容,直到读到文件末尾结束
{
if(buf[strlen(buf)-1] == '\n')//判断是否读到新行符
line++;
}
printf("line = %d\n",line);
return 0;
}
效果图:
2>
要求:
源代码:
#include "myhead.h"
int main(int argc, char const *argv[])
{
FILE *src = NULL;
if ((src = fopen("./t1.txt", "r")) == NULL)
{
perror("fopen error");
return -1;
}
FILE *dest = NULL;
if ((dest = fopen("./t12.txt", "w+")) == NULL)
{
perror("fopen error");
return -1;
}
char buf[128];
while ((fgets(buf, sizeof(buf) - 1, src)) != NULL)
{
fputs(buf, dest);
}
fclose(src);
fclose(dest);
return 0;
}
效果图:
3>
要求:
源代码:
#include "myhead.h"
void sign_in();
void log_in();
int main(int argc, char const *argv[])
{
int menu = 0;
while (1)
{
//system("clear");
printf("\t\t=========XXX登入界面XXX=======\n\n");
printf("\t\t=========1-注册=======\n");
printf("\t\t=========2-登入=======\n");
printf("\t\t=========0-退出=======\n");
printf("请输入选项:");
scanf("%d", &menu);
getchar();
switch (menu)
{
case 1:
{
sign_in();
}
break;
case 2:
{
log_in();
}
break;
case 0:
exit(-1);
break;
default:
printf("您输入功能有误,请重新输入:\n");
}
printf("输入任意键按回车结束\n");
while (getchar() != '\n')
;
}
return 0;
}
// 注册函数
void sign_in()
{
FILE *fp = NULL; // 操作文件的句柄
if ((fp = fopen("./sign.txt", "a+")) == NULL)
{
perror("fopen error");
return;
}
char id[50] ;//定义用户名所用字符串
char password[50];//定义密码所用字符串
//将终端输入写入id和password字符数组中,再通过fp写进文件中
printf("请输入账户:");
fgets(id, sizeof(id), stdin);
fputs(id, fp);
printf("请输入密码:");
fgets(password, sizeof(password), stdin);
fputs(password, fp);
printf("sign in success\n");
fclose(fp);
}
// 登录函数
void log_in()
{
FILE *fp = fopen("./sign.txt", "r");//已只读的方式打开文件
if (fp == NULL)
{
perror("fopen error");
return;
}
//将终端输入记录在对应字符数组中,方便以后比较
char id[64] = "";
printf("请输入帐号:");
fgets(id, sizeof(id) - 1, stdin);
char password[64] = "";
printf("请输入密码:");
fgets(password, sizeof(password) - 1, stdin);
char buf1[64];//用来读取第一行
char buf2[64];//用来读取第二行
while (1) // 两行一组,遍历fp来匹配
{
//直到fp到文件末尾还没匹配才输出error
if (fgets(buf1, sizeof(buf1), fp) == NULL)
{
printf("log in error\n");
break;
}
fgets(buf2, sizeof(buf2), fp);
//只要有一组匹配就break
if (strcmp(id, buf1) == 0 && strcmp(password, buf2) == 0)
{
printf("log in success\n");
break;
}
}
fclose(fp);
}
效果图: