简体   繁体   English

fscanf在C中两次从文件复制一行

[英]fscanf copies a line from file twice in C

                while(1<2) {
                    nscan=fscanf(infile, "%s %s %d%c",temp.name, temp.surname,&temp.code,&termch);
                    if(nscan==EOF) break;
                    if(nscan!=4 || termch!='\n')
                        printf("Error\n");
                    RecBSTInsert(&a,temp);

             }

for some reason nscan //if(nscan==EOF) break; 由于某种原因nscan // if(nscan == EOF)break; does not get executed when it is supposed to and it runs one more time giving the binary tree one more value, which is same with the last one. 不会在应有的情况下执行,它又运行了一次,为二进制树提供了另一个值,该值与最后一个相同。

fscanf: fscanf:

Upon successful completion, these functions shall return the number of successfully matched and assigned input items. 成功完成后,这些功能应返回成功匹配和分配的输入项目的数量。

fscanf does not return the input provided. fscanf不返回提供的输入。 That is why you are not seeing EOF like you are testing for. 这就是为什么您没有看到正在测试的EOF的原因。

See: manpage for *scanf functions. 请参见:手册页以获取* scanf函数。


To answer your other question, try looping through like this: 要回答您的其他问题,请尝试像这样循环遍历:

while (fscanf(infile, "%s %s %d%c, temp.name, temp.surname, &temp.code, &termch) == 4)
{
    //...
}

Edit again: I threw together a small program to simulate what I think you are doing. 再次编辑:我整理了一个小程序来模拟我认为您在做什么。 Here is my implementation, which takes from a file "testfile.txt" which looks like: 这是我的实现,它取自文件“ testfile.txt”,如下所示:

Bill Person 1 比尔1

Bob Dog 2 鲍勃狗2

Andrew Cat 3 安德鲁猫3

With only one newline between each line. 每行之间只有一个换行符。 It matches the pattern %s %s %d%c (where \\n is the %c). 它与模式%s%s%d%c(其中\\ n是%c)匹配。

Program to use this file: 使用此文件的程序:

#include <stdio.h>
#include <stdlib.h>

struct test {
    char name[64];
    char surname[64];
    int code;
};

int main()
{
    struct test temp;
    char endchar;
    FILE *infile = fopen("./testfile.txt", "r+"); // works with "r" as well, just a habit
    if (infile == NULL)
        return -1;
    while (fscanf(infile, "%s %s %d%c", temp.name, temp.surname, 
                  &temp.code, &endchar) == 4)
    {
        printf("Got one!\n");
    }
    return 0;
}

Of course, the printf exists in place of whatever logic you want to do on the current "temp" input. 当然, printf代替您要对当前“临时”输入执行的任何逻辑操作。

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

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