简体   繁体   English

fscanf函数无法在c中读取

[英]fscanf function doesn't read in c

I tried to read some data from file and insert it to queue, Insert function works well, and i tried to catch the error with printfs. 我试图从文件中读取一些数据并将其插入队列,Insert函数运行良好,并且我尝试使用printfs捕获错误。 I saw that in while() line there is error. 我在while()行中看到错误。 The data in file forms like that 像这样的文件形式的数据

12345 2 12345 2

11232 4 11232 4

22311 4 22311 4

22231 2 22231 2

void read_file(struct Queue *head){
FILE *fp;
int natid;
int cond;
fp=fopen("patients.txt","r");

    while (fscanf(fp,"%d %d", natid, cond) != EOF)
        insert(head,natid,cond);

fclose(fp);}
while (fscanf(fp,"%d %d", natid, cond) != EOF)

should be 应该

while (fscanf(fp,"%d %d", &natid, &cond) == 2)

You need to pass the address of natid and cond instead of its value as the %d s in fscanf expects an int* , not an int . 您需要传递natidcond的地址而不是其值,因为fscanf%d s需要一个int* ,而不是int And I've used == 2 so that the loop breaks in case of EOF or invalid data(like characters). 而且我使用== 2以便在EOF或无效数据(例如字符)的情况下中断循环。 Otherwise, if the file contains invalid data, the loop will turn into an infinite loop as %d will fail to scan an integer. 否则,如果文件包含无效数据,则循环将变成无限循环,因为%d将无法扫描整数。


You should also check if fopen was successful. 您还应该检查fopen是否成功。 fopen returns NULL in failure. 如果失败, fopen将返回NULL

您必须将指针传递到fscanf()将存储值的位置,并检查所有预期的转换是否成功:

while (fscanf(fp, "%d %d", &natid, &cond) == 2)

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

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