简体   繁体   English

在C中无法从二进制文件读取

[英]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 . 我正在使用C编程语言,并试图读取二进制File中每一行的第一个字符串。

Example of data in the binary file (I have written to a txt file in order to show you) 二进制文件中的数据示例(为了显示给您,我已写入txt文件)

Iliya Iliya Vaitzman 16.00 israel 1 0 1 Iliya Iliya Vaitzman 16.00以色列1 0 1

I want to read to first Iliya in the line (or what ever the first word in the line will be). 我想阅读该行的第一个Iliya(或该行的第一个单词将是什么)。

I am trying the following code but it keeps returning NULL to the string variable I gave him 我正在尝试以下代码,但它始终将NULL返回给我给他的字符串变量

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)) 我将typedef和#define用作布尔变量(0为false,其他所有条件为true(TRUE为true,FALSE为false))

usernameRecieved keeps getting NULL from the fread . usernameRecieved不断从fread中获取NULL。

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). 有两件事:您将fread中的count字段设置为1,因此最多只能读取1个字节(假设您未触及EOF或其他终端标记)。 It's likely that what you want is: 您可能想要的是:

fread(usernameRecieved, 1, 31, ptrMyFile);

That way you'll copy into your whole char buffer. 这样,您将复制到整个char缓冲区中。 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保持为空”的含义。 usernameRecieved is on the stack (you aren't using malloc). usernameRecieved在堆栈上(您未使用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; 我强烈建议您始终检查fread的返回值以查看读取了多少。 this is helpful in debugging. 这对调试很有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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