1. 使用fgets统计给定文件的行数
#include <stdio.h>
#include <stdlib.h>
#include <string.h>int main(int argc, char const *argv[])
{if (argc != 2){puts("input file error");puts("usage:./a.out filename");return -1;}FILE* fp = NULL;if ((fp = fopen(argv[1], "r")) == NULL){perror("fopen error");return -1;}int count = 0;char buf[5];while (1){fgets(buf, sizeof(buf), fp);if (strlen(buf) == 0){break;}printf("%s", buf);for (int i = 0; i < 5; i++){if (buf[i] == '\n'){count++;}}memset(buf, 0, sizeof(buf));}printf("%d\n", count);return 0;
}
2. 使用fputs和fgets完成两个文件的拷贝
#include <stdio.h>
#include <stdlib.h>
#include <string.h>#define MAXSIZE 10FILE* open_file(char name[], char method[])
{FILE* fp = NULL;if ((fp = fopen(name, method)) == NULL){return NULL;}return fp;
}int main(int argc, char const *argv[])
{if (argc != 3){puts("input file error");puts("usage:./a.out srcfile destfile");return -1;}FILE* fp = open_file(argv[1], "r");if (NULL == fp){perror("fopen error");return -1;}FILE* fp1 = open_file(argv[2], "w");if (NULL == fp1){perror("fopen error");return -1;}char buf[MAXSIZE];while (1){fgets(buf, sizeof(buf), fp);if (strlen(buf) == 0){break;}fputs(buf, fp1);memset(buf, 0, sizeof(buf));}fclose(fp);fclose(fp1);return 0;
}
3. 完成登录注册功能
做个小菜单,功能1是注册功能,输入注册账户和注册密码,将账户和密码写入文件中
功能2是登录功能,提示输入登陆账户和登录密码,并用其遍历文件中的每一组账户和密码,如果匹配成功,则登录成功,如果全部不匹配则提示登陆失败
#include <stdio.h>
#include <stdlib.h>
#include <string.h>#define MAXSIZE 100FILE* open_file(char name[], char mode[])
{FILE* fp = NULL;if ((fp = fopen(name, mode)) == NULL){return NULL;}return fp;
}void read_and_save(FILE* src, FILE* dest)
{char buf[MAXSIZE];fgets(buf, sizeof(buf), src);fputs(buf, dest);
}void sign_up()
{FILE* fp = open_file("test.txt", "a+");if (NULL == fp){perror("fopen error");return;}printf("请输入用户名:");read_and_save(stdin, fp);printf("请输入密码:");read_and_save(stdin, fp);fclose(fp);puts("注册成功!");puts("");
}void login()
{FILE* fp = open_file("test.txt", "a+");if (NULL == fp){perror("fopen error");return;}char username[MAXSIZE], passwd[MAXSIZE];printf("请输入用户名:");fgets(username, sizeof(username), stdin);printf("请输入密码:");fgets(passwd, sizeof(passwd), stdin);char buf1[MAXSIZE], buf2[MAXSIZE];while (1){fgets(buf1, sizeof(buf1), fp);if (strlen(buf1) == 0){puts("登录失败!");puts("");break;}fgets(buf2, sizeof(buf2), fp);if (strcmp(username, buf1) == 0 && strcmp(passwd, buf2) == 0){puts("登录成功!");puts("");break;}memset(buf1, 0, sizeof(buf1));memset(buf2, 0, sizeof(buf2));}fclose(fp);
}int main(int argc, char const *argv[])
{int flag = 1;while (flag){printf("====================\n");printf("------ 登录界面 -----\n");printf("-------1、注册-------\n");printf("-------2、登录-------\n");printf("-------0、退出-------\n");printf("====================\n");printf("请输入选项:");int menu;scanf("%d", &menu);getchar();switch (menu){case 1:sign_up();break;case 2:login();break;case 0:flag = 0;break;default:break;}}return 0;
}