作业1:使用分文件编译,实现注册登录界面,使用已经学过的fgets,fscanf,fpritnf函数。
#include <myhead.h>
void registerUser() {
char username[50], password[50];
printf("请输入用户名: ");
fgets(username, sizeof(username), stdin);
printf("请输入密码: ");
fgets(password, sizeof(password), stdin);
// 移除换行符
username[strcspn(username, "\n")] = 0;
password[strcspn(password, "\n")] = 0;
FILE *fp = fopen("users.txt", "a");
if (fp == NULL) {
printf("无法打开文件\n");
return;
}
fprintf(fp, "%s %s\n", username, password);
fclose(fp);
printf("注册成功!\n");
}
#include <myhead.h>
bool loginUser() {
char username[50], password[50];
printf("请输入用户名: ");
fgets(username, sizeof(username), stdin);
printf("请输入密码: ");
fgets(password, sizeof(password), stdin);
// 移除换行符
username[strcspn(username, "\n")] = 0;
password[strcspn(password, "\n")] = 0;
FILE *fp = fopen("users.txt", "r");
if (fp == NULL) {
printf("无法打开文件\n");
return false;
}
char line[100];
while (fgets(line, 100, fp)) {
char *token = strtok(line, " ");
if (strcmp(token, username) == 0) {
token = strtok(NULL, " ");
if (strcmp(token, password) == 0) {
fclose(fp);
printf("登录成功!\n");
return true;
}
}
}
fclose(fp);
printf("用户名或密码错误。\n");
return false;
}
#include <myhead.h>
#include "register.c"
#include "login.c"
int main() {
int choice;
do {
printf("\n请选择操作:\n");
printf("1. 注册\n");
printf("2. 登录\n");
printf("3. 退出\n");
printf("输入选项: ");
scanf("%d", &choice);
switch (choice) {
case 1:
registerUser();
break;
case 2:
if (!loginUser()) {
printf("登录失败。\n");
}
break;
case 3:
printf("退出程序。\n");
break;
default:
printf("无效选项,请重新输入。\n");
break;
}
} while (choice != 3);
return 0;
}
作业2:使用fread和fwrite拷贝文件。
#include <myhead.h>
int main(int argc, char *argv[])
{
if(argc != 3)//输入三个命令行参数
{
printf("Usage: %s 1.txt 2.txt\n", argv[0]);
return -1;
}
FILE *fp1 = fopen(argv[1], "r+");
if(NULL == fp1)
{
perror("open");
return -1;
}
FILE *fp2 = fopen(argv[2], "w+");
if(NULL == fp1)
{
perror("open");
return -1;
}
int ret;
char buf[64] = {0};
while((ret = fread(buf, sizeof(char), 1, fp1) != 0))
{
fwrite(buf, sizeof(char), 1, fp2);
}
return 0;
}