1、计算文件的行数和大小
#include <stdio.h>
int main(int argc, const char *argv[])
{
if(argc < 2) {
printf("请输入文件名\n");
return -1;
}
FILE *fp = fopen(argv[1], "r");
int line_count = 0;
int data_count = 0;
char c = 0;
while(1)
{
c = fgetc(fp);
if(c == EOF)
{
break;
}
if(c == '\n')
{
line_count++;
}
data_count++;
}
printf("%s有%d行,大小是%d字节.\n", argv[1], line_count, data_count);
fclose(fp);
return 0;
}
2、
#include <stdio.h>
#include <errno.h>
#include <string.h>
int user_login();
int user_inset();
int main(int argc, const char *argv[])
{
int choice_num=0;
while(1)
{
printf("登录选1,注册选择2,输入其他退出.\n");
scanf("%d", &choice_num);
if(1 == choice_num)
{
user_login();
}else if(2 == choice_num)
{
user_inset();
}else
{
break;
}
}
return 0;
}
//注册
int user_inset()
{
char usname[20], uspasswd[20];
char in_usname[20] = "0";
int flag =0;
FILE *fp = fopen("./user.txt", "r");
if(!fp)
{
perror("foprn");
return -1;
}
while(1)
{
printf("请输入注册的用户名\n");
scanf("%s", in_usname);
while(1)
{
if(fscanf(fp, "%s %s", usname, uspasswd) < 0)
{
if(!errno)
{
break;
}else
{
printf("read error\n");
return -1;
}
}
if(!strcmp(in_usname, usname))
{
flag = 1;
printf("用户名已存在\n");
break;
}
}
if(!flag)
{
break;
}
flag = 0;
}
fclose(fp);
FILE *fp_write = fopen("./user.txt", "a");
if(!fp_write)
{
perror("fopen");
return -1;
}
printf("请输入密码\n");
scanf("%s", uspasswd);
fprintf(fp_write, "%s %s\n", in_usname, uspasswd);
fclose(fp_write);
return 0;
}
//登录
int user_login()
{
FILE *fp = fopen("./user.txt", "r");
if(!fp)
{
printf("read error\n");
return -1;
}
printf("请输入用户名和密码\n");
char name[20]="0", passwd[20]="0";
scanf("%s", name);
scanf("%s", passwd);
printf("%s %s\n", name, passwd);
char usname[20]="0", uspasswd[20]="0",flag=0;
while(1)
{
if(fscanf(fp, "%s %s", usname, uspasswd) < 0)
{
if(0 == errno)
{
break;
}else
{
printf("read error!\n");
return -1;
}
}
if(!strcmp(name, usname))
{
flag = 1;
if(!strcmp(passwd, uspasswd))
{
printf("用户名密码正确,登录成功\n");
return 1;
}else
{
printf("密码错误\n");
return -1;
}
}
}
if(!flag)
{
printf("没有这个用户\n");
}
return 0;
}