简体   繁体   中英

Reading from binary file is unsuccessful in C

I am using C programming language and am trying to read the first string of every line in a binary File .

Example of data in the binary file (I have written to a txt file in order to show you)

Iliya Iliya Vaitzman 16.00 israel 1 0 1

I want to read to first Iliya in the line (or what ever the first word in the line will be).

I am trying the following code but it keeps returning NULL to the string variable I gave him

The following code:

FILE* ptrMyFile;
    char usernameRecieved[31];
    boolean isExist = FALSE;
    ptrMyFile = fopen(USERS_CRED_FILENAME, "a+b");
    if (ptrMyFile)
    {
        while (!feof(ptrMyFile) && !isExist)
        {
            fread(usernameRecieved, 1, 1, ptrMyFile);
            if (!strcmp(userName, usernameRecieved))
            {
                isExist = TRUE;
            }
        }
    }
    else
    {
        printf("An error has encountered, Please try again\n");
    }
    return isExist;

I used typedef and #define to a boolean variable (0 is false, everything else is true (TRUE is true, FALSE is false))

usernameRecieved keeps getting NULL from the fread .

What should I do in order to solve this?

Instead of this:

fread(usernameRecieved, 1, 1, ptrMyFile);

try this:

memset(usernameRecieved, 0, sizeof(usernameRecieved));
fread(usernameRecieved, sizeof(usernameRecieved)-1, 1, ptrMyFile);

As it is, you are reading at most only one byte from the file.

Documentation on fread

A couple things: you're setting the count field in fread to 1, so you'll only ever read 1 byte, at most (assuming you don't hit an EOF or other terminal marker). It's likely that what you want is:

fread(usernameRecieved, 1, 31, ptrMyFile);

That way you'll copy into your whole char buffer. You'll then want to compare only up to whatever delimiter you're using (space, period, etc).

It's not clear what "usernameRecieved keeps getting NULL" means; usernameRecieved is on the stack (you aren't using malloc). Do you mean that nothing is being read? I highly suggest that you always check the return value from fread to see how much is read; this is helpful in debugging.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM