简体   繁体   English

我如何从文件中读取结构?

[英]How can i read struct from a file?

struct Country{
    char name[50];
    float square;
    float quantityOfPeople;
};
 while (fread(&newRecord,sizeof(struct Country),1,fout)) {
        printf("hello\n");
        if (strcmp (countryName, newRecord.name) == 0) {
            printf("A record with requested name found and deleted.\n\n");
            found=1;
        } else {
            fwrite(&newRecord, sizeof(struct Country), 1, fp_tmp);
        }

    }

my file is我的文件是

hjk
78.699997
799.900024

america
3432.300049
2323.199951

ghi
78.900002
89.000000

dmdmd
746234052608.000000
0.000000

In my file there is 4 records of country so it should print 4 times hellp, but it prints hello twice.在我的文件中有 4 个国家/地区记录,因此它应该打印 4 次 hellp,但它打印了两次 hello。 The main task is to remove the duplicate entry in the file.主要任务是删除文件中的重复条目。

fread(&newRecord,sizeof(struct Country),1,fout) is for reading binary data from a file. fread(&newRecord,sizeof(struct Country),1,fout)用于从文件中读取二进制数据。

OP's file is text based. OP 的文件是基于文本的。


How can i read struct from a file?我如何从文件中读取结构?

Open the file in text mode.以文本模式打开文件。

Form a helper function that reads 4 lines with 4x fgets() and then processes the lines for 1) country name, 2) some double (see strod() ) 3) another double and 4) an optional empty line.形成一个辅助函数,该函数使用 4x fgets()读取 4,然后处理以下行:1) 国家/地区名称,2) 一些double精度数(请参阅strod() )3) 另一个double精度数和 4) 一个可选的空行。

If all these pass, save in a struct Country如果所有这些都通过,保存在一个struct Country

Return 1 for success, 0 for failure, EOF for nothing read.返回 1 表示成功,0 表示失败, EOF表示未读取任何内容。

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

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