这个程序中的fread有什么问题? [英] Whats wrong with fread in this program?

查看:122
本文介绍了这个程序中的fread有什么问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是C的中级学生。我试图做一个银行管理程序,但首先我需要一个登录程序,所以我创建了以下之一。因为我最近了解到在C中的文件I / O,不太了解fread和fwrite。我有一个文件(data.txt),格式如下:

I'm intermediate student of C. I'm trying to make a bank management program but first I need to make a login program, so I created one of the following. As I've recently learned about file I/O in C and don't know much about fread and fwrite. I have a file (data.txt) which format if as following.

user1 1124

user1 1124

user2 3215

user2 3215

user3 5431

user3 5431

在以下程序中,我要求用户输入用户名和PIN密码)并将文件数据复制到一个结构中,然后比较这两个用于验证信息。

In the following program I've asked user to input user name and pin(4-digit password) and copy file data into a structure then compare these two for verifying information.

我的程序有什么问题,以及如何使fread正常工作。

What is wrong with my program and how to make fread work properly. And is the formating in data.txt file all right or should I change it.

提前感谢...

#include<stdio.h>
#include<ctype.h>
#include<string.h>

struct user_account    {
    char u_name[30];
    int u_pin;
} log_in;



    int login()
{
    int start;
    int i, n;
    int t_pin[4];       // TEMPORARY INT PIN for storing pin inputed by user
    char t_name[30];    //  TEMPORARY STRING for storing name inputed by user

    FILE *fp;
    fp = fopen("data.txt","rb");        // Opening record file

    if(fp == NULL)
    {
    puts("Unable to open file!");
    return 1;
    }

    start :  {
        printf("User Name : ");
        scanf("%s",&t_name);
        printf("Pin Code  : ");

        for(i = 0; i < 4; i++)  {       // This loop is for hiding input pin
            n = getch();

            if(isdigit(n))  {
                t_pin[i] = n;
                printf("*");    }
            else    {
                printf("\b");
                i--;
            }
        }

        fread(&log_in,sizeof(log_in),1,fp);

        // Comparing user name and pin with info in the structure copied from the file

        if(strcmp(log_in.u_name, t_name) == 0 && log_in.u_pin == t_pin)
            puts("Login successful! Welcome User");
        else    {
            printf("\nIncorrect Information!\n");
            printf("Press any key to log in again...");
            getch();
            system("cls");
            goto start; }
        }
    }

    int main()
    {
    int login();
        return 0;
    }


推荐答案

问题是一个ASCII /文本文件,但您试图使用 fread 直接读入结构;这需要一个二进制格式的文件。 fread 无法进行格式转换。请改用 fscanf

The problem is that you have an ASCII/text file but you are trying to use fread to read directly into a structure; this requires a binary formatted file. fread cannot do format conversion. Use fscanf instead:

fscanf(fp, "%s %d", &log_in.u_name, &log_in.u_pin);

这篇关于这个程序中的fread有什么问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆