#include
int main(int argc, const char *argv[])
{
FILE *p=fopen("1.txt","a+");
FILE *p2=fopen("2.txt","w+");
int r=0;
int count=0;
int row=0;
while(1){
r=fgetc(p);
if(EOF==r)
break;
count++;
fputc(r,p2);
if(r=='\n'){
row++;
}
}
printf("1.txt字节大小为:%d\n",count);
printf("1.txt行数为:%d\n",row);
count=0;
row=0;
fclose(p2);
p2=fopen("2.txt","r");
while((r=fgetc(p2))!=EOF){
count++;
if(r=='\n')
row++;
}
printf("2.txt字节大小为:%d\n",count);
printf("2.txt行数为:%d\n",row);
return 0;
}
#include
#include
int main(int argc, const char *argv[])
{
FILE *fp=fopen("io.c","a+");
FILE *f=fopen("1.txt","a+");
if(NULL==fp){
perror("fopen");
}else{
printf("运行成功\n");
}
char i[127]={0};
/*字符串*/
while(EOF!=fscanf(fp,"%126[^\n]",i))
{
//fscanf(fp,"%[^\n]",i);
printf("%s\n",i);
fprintf(f,"%s\n",i);
fgetc(fp); // 添加这一行来消耗掉换行符
i[0] = '\0'; // 清除i数组的内容
}
if(fclose(fp)<0){
perror("fclose");
return -1;
}
printf("fclose success\n");
return 0;
}
作业
1.
实现登录功能。自定义一个usr.txt,手动输入账户密码,格式如下:账户 密码
例如: zhangsan 12345
lisi abcde
wangwu abc123
需求如下:
a.
从终端获取账户密码,与文件中的账户密码比较
b.
若终端输入的账户不存在,则输出账户不存在
c.
若终端输入的账户存在,但是密码不正确,则输出密码错误
d.
若账户密码均正确,则输出登录成功
2.
附加题
实现注册功能,注册的账户密码存储在上一题的文件中。需求:不能重复注册。
#include
#include
void register_account() {
FILE *DL = fopen("usr.txt", "a+");
if(NULL == DL) {
printf("打开失败\n");
perror("fopen");
return;
}
char zh[13] = {0};
char mm[16] = {0};
char a[13] = {0};
char b[16] = {0};
printf("开始注册\n");
printf("输入账号(12位以内):");
scanf("%12s", zh);
getchar();
printf("输入密码(15位以内):");
scanf("%15s", mm);
getchar();
while(fscanf(DL, "%12s %15s", a, b) != EOF) {
if(0 == strcmp(zh, a)) {
printf("账号已存在,不能重复注册。\n");
fclose(DL);
return;
}
}
fprintf(DL, "%s %s\n", zh, mm);
printf("注册成功\n");
fclose(DL);
}
int login() {
FILE *DL = fopen("usr.txt", "r");
if(NULL == DL) {
printf("打开失败\n");
perror("fopen");
return -1;
}
char dlzh[13] = {0};
char dlmm[16] = {0};
char a[13] = {0};
char b[16] = {0};
printf("输入账号(12位以内):");
scanf("%12s", dlzh);
getchar();
printf("输入密码(15位以内):");
scanf("%15s", dlmm);
int scanResult;
while((scanResult = fscanf(DL, "%12s %15s", a, b)) != EOF) {
if(0 == strcmp(dlzh, a)) {
if(0 == strcmp(dlmm, b)) {
printf("登录成功\n");
fclose(DL);
return 1;
} else {
printf("密码错误\n");
fclose(DL);
return -1;
}
}
}
if(scanResult == EOF) {
printf("账户不存在\n");
fclose(DL);
return -1;
}
}
int main(int argc, const char *argv[]) {
int choice;
while(1) {
printf("1. 注册\n");
printf("2. 登录\n");
printf("3. 退出\n");
printf("选择操作:");
scanf("%d", &choice);
// getchar();
switch(choice) {
case 1:
register_account();
break;
case 2:
if(1==login())
return 0;
break;
case 3:
return 0;
default:
printf("无效选择!\n");
}
}
}