文件读取复制与拷贝

作业1:使用分文件编译,实现注册登录界面,使用已经学过的fgets,fscanf,fpritnf函数。

main.c

#include "1.h"

int main(int argc, const char *argv[])
{
	int choise=3;
	while(1){
		printf("1.注册。2.登录。3.退出");
		scanf(" %d",&choise);
		switch(choise){
			case 1:
				regist();
				break;
			case 2:
				login();
				break;
			case 3:
				exit(EXIT_SUCCESS);
				break;
		}
	}



	return 0;
}

1.h

#ifndef _LOGREG_
#define _LOGREG_
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

typedef struct{
	char account[20];
	char password[20];
}user;

int login();
int regist();

#endif

func.c,这边的重点就是读取之间用“ ”空格分隔,不是表示空格,而是忽视隔断符号。存入\n用于更好分隔。

#include "1.h"

//清除缓存
void clear_buf(){
    char c;
    while((c = getchar()) != EOF && c != '\n');
}

int regist(){
    clear_buf();
    user reg;
    FILE *fp = fopen("./1.txt", "w");
    if(fp == NULL) {
        printf("无法打开文件,注册失败\n");
        return -1;
    }
    printf("请输入账号\n");
    fgets(reg.account, sizeof(reg.account), stdin);
    reg.account[strcspn(reg.account, "\n")] = '\0';  // 去除换行符
    printf("请输入密码\n");
    fgets(reg.password, sizeof(reg.password), stdin);
    reg.password[strcspn(reg.password, "\n")] = '\0';  
    fprintf(fp, "%s\n%s", reg.account, reg.password);  
    fclose(fp);
    printf("注册成功\n");
    return 0;
}

int login(){
    clear_buf();
    user reg, log;
    FILE *fp = fopen("./1.txt", "r");
    if(fp == NULL) {
        printf("无法打开文件,登录失败\n");
        return -1;
    }

    printf("请输入账号\n");
    fgets(log.account, sizeof(log.account), stdin);
    log.account[strcspn(log.account, "\n")] = '\0';  // 去除换行符
    printf("请输入密码\n");
    fgets(log.password, sizeof(log.password), stdin);
    log.password[strcspn(log.password, "\n")] = '\0'; 

    // 读取文件中的账号和密码
    fscanf(fp, "%s %s", reg.account, reg.password);
    printf("从文件读取的账号: '%s', 密码: '%s'\n", reg.account, reg.password);
    fclose(fp);

    // 比较账号和密码
    if(strcmp(log.account, reg.account) == 0 && strcmp(log.password, reg.password) == 0) {
        printf("登录成功\n");
    } else {
        printf("账号或密码错误,登录失败\n");
    }

    return 0;
}

作业2:使用fread和fwrite拷贝文件。参数为(缓存地址,次数,大小,FILE指针),返回读取个数。

#include <stdio.h>
#include <string.h>
int main(int argc, const char *argv[])
{
	FILE *fr=fopen("./1.txt","rb");
	FILE *fw=fopen("./2.txt","wb");
     char buf[200];  // 缓冲区,用于存储读取的数据
    size_t bytes_read;

    // 循环读取源文件的数据并写入到目标文件中
    while ((bytes_read = fread(buf, 1, sizeof(buf), fr)) > 0) {
        fwrite(buf, 1, bytes_read, fw);
    }

    printf("文件拷贝完成!\n");
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值