使用fgets统计给定文件的行数
#include<stdio.h>
#include<string.h>
int main(int argc, const char *argv[])
{
FILE *fp=NULL;
if((fp=fopen("./test.txt","w"))==NULL)
{
perror("open err");
return -1;
}
fputc('h',fp);
fputc('\n',fp);
fputc('e',fp);
fputc('l',fp);
fputc('\n',fp);
fputc('\0',fp);
fclose(fp);
int line=0;
if((fp=fopen("./test.txt","r"))==NULL)
{
perror("open err");
return -1;
}
char ch=0;
while(1)
{
ch=fgetc(fp);
if(ch=='\n')
{
line++;
}
else if(ch==EOF)
{
line++;
break;
}
}
printf("%d\n",line);
fclose(fp);
return 0;
}
使用fputs和fgets完成两个文件的拷贝
#include<stdio.h>
#include<string.h>
int main(int argc, const char *argv[])
{
FILE *fp=NULL;
FILE *fp1=NULL;
if((fp=fopen("./test.txt","w"))==NULL)
{
perror("open err");
return -1;
}
fputs("hello",fp);
fclose(fp);
if((fp=fopen("./test.txt","r"))==NULL)
{
perror("open err");
return -1;
}
char ch[1000]="";
if((fp1=fopen("./test1.txt","w"))==NULL)
{
perror("open err");
return -1;
}
while(1)
{
char *c=fgets(ch,sizeof(ch),fp);
if(c==NULL)
{
break;
}
else
{
fputs(ch,fp1);
}
}
fclose(fp);
fclose(fp1);
return 0;
}
完成注册登录功能
做个小菜单,功能1是注册功能,输入注册账户和注册密码,将账户和密码写入文件中
功能2是登录功能,提示并输入登录账户和登录密码,并用其遍历文件中的每一组账户和密码,如果匹配成功,则登录成功,如果全部不匹配则提示登录失败
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main(int argc, const char *argv[])
{
FILE *fp=NULL;
FILE *fp1=NULL;
while(1)
{
printf("登录界面\n");
printf("1.注册\n");
printf("2.登录\n");
printf("0.退出\n");
int meau=0;
char username [10000]="";
char password[10000]="";
char username1[10000]="";
char password1[10000]="";
scanf("%d",&meau);
switch(meau)
{
case 1:
{
printf("username:\n");
scanf("%s",username);
int lenname=strlen(username);
if((fp=fopen("./username.txt","w"))==NULL)
{
puts("open err");
return -1;
}
for(int i=0;i<lenname;i++)
{
fprintf(fp,"%c",username[i]);
}
fclose(fp);
printf("password:\n");
scanf("%s",password);
int lenpass=strlen(password);
if((fp1=fopen("./password.txt","w"))==NULL)
{
puts("open err");
return -1;
}
for(int i=0;i<lenpass;i++)
{
fprintf(fp1,"%c",password[i]);
}
fclose(fp1);
}
break;
case 2:
{
printf("username:\n");
scanf("%s",username);
int lenname=strlen(username);
printf("password:\n");
scanf("%s",password);
int lenpass=strlen(password);
if((fp=fopen("./username.txt","r"))==NULL)
{
puts("open err");
return -1;
}
if((fp1=fopen("./password.txt","r"))==NULL)
{
puts("open err");
return -1;
}
for(int i=0;i<lenname;i++)
{
fscanf(fp,"%c",&username1[i]);
}
for(int i=0;i<lenpass;i++)
{
fscanf(fp1,"%c",&password1[i]);
}
int len=lenname>lenpass?lenname:lenpass;
for(int i=0;i<len;i++)
{
if (password[i]==password1[i]&&username[i]==username1[i])
{
if(i+1==len)
{
puts(username);
puts(password);
puts("success");
}
}
else if (password[i]!=password1[i]&&username[i]!=username1[i])
{
puts("error");
break;
}
}
}
break;
case 0:goto END;
default:puts("input cd is error");
}
}
END:
return 0;
}