害怕不推进指针

fread not advancing the pointer

我在 C 中使用 fread()。我正在尝试读取二进制文件名 pds_demo.bin 的内容,但不知何故我的 fread 功能没有推进。我在 gdb 中检查了 fread() 的返回值,它返回 0.

我总共使用了 3 个文件 pds_functions.cpds_test.cpds_demo.bin(包含要读取的数据)。

pds_test.c 正在调用 pds_functions.c 中名为 pds_search_by_key() 的函数来检查特别的。此函数检查演示文件的内容和 returns 记录是否存在的状态。我已经包含了以下所有文件。

如有任何帮助,我们将不胜感激。谢谢。

pds_test.c:

void test_search() {
    int status;
    struct Contact c3;
    int key;
    key = 101;
    status = pds_search_by_key(key, &c3);
    if (status != PDS_SUCCESS) {
        fprintf(stderr, "pds_search_by_key failed for key %d: errorcode %d\n", key, status);
    } else {
        printContact(&c3);
    }
    key = 102;
    status = pds_search_by_key(key, &c3);
    if (status != PDS_SUCCESS) {
        fprintf(stderr, "pds_search_by_key failed for key %d: errorcode %d\n", key, status);
    } else {
        printContact(&c3);
    }
    key = 1020000;
    status = pds_search_by_key(key, &c3);
    if (status != PDS_SUCCESS) {
        fprintf(stderr, "pds_search_by_key failed for key %d: errorcode %d\n", key, status);
    } else {
        printContact(&c3);
    }
}

pds_functions.c:

int pds_search_by_key(int key, struct Contact *c) {

    fseek(repo_fptr, 0L, 0);

    if (pdsInfo.repo_status == 1) {
        while (!feof(repo_fptr)) {
            fread(c, sizeof(struct Contact), 1, repo_fptr);
            if (c->contact_id == key) {
                return PDS_SUCCESS;
            }
        }
        return PDS_REC_NOT_FOUND;
    }
    return PDS_REPO_NOTOPEN;
}

pds_demo.bin:

101 Contact #1 Phone #1 Email #1 102 Contact #2 Phone #2 Email #2 102 Contact #2 Phone #2 Email #2 

还有一个定义结构 Contact 的结构。

struct Contact {
    int contact_id;
    char cname[MAX_NAME_LEN];
    char mphone[MAX_PHONE_LEN];
    char email[MAX_EMAIL_LEN];
};

另外我用gdb调试程序时*c的内容如下:

(gdb) p *c
 = {contact_id = 540094513, cname = "Contact #1 Phone #1 Email #1 102 
Contact #2 Phone ", mphone = "#2 Email #2", 
  email = " 102 Contact #2 Phone #2 Email #2 777[=14=]0[=14=]0\t\t@[=14=]0[=14=]0[=14=]0[=14=]0[=14=]0[=14=]0[=14=]0"}

您的代码存在重大问题:

  • 你的阅读循环不正确,原因在这里:Why is “while ( !feof (file) )” always wrong?

  • 您正在从文件中读取固定长度的结构,您必须以二进制方式读写文件,fopen必须通过"rb""wb"分别以二进制模式打开文件。

如果文件以二进制模式打开,读取循环可以这样修改:

int pds_search_by_key(int key, struct Contact *c) {

    fseek(repo_fptr, 0L, 0);

    if (pdsInfo.repo_status == 1) {
        while (fread(c, sizeof(*c), 1, repo_fptr) == 1) {
            if (c->contact_id == key) {
                return PDS_SUCCESS;
            }
        }
        return PDS_REC_NOT_FOUND;
    }
    return PDS_REPO_NOTOPEN;
}