0

我有一个文件 data.dat

HI5 LO2

我想从中读取 5 和 2,并将它们存储为 uint16s。我写过

#include <stdio.h>
int main()
{
    unsigned short int high;
    FILE *pFile;
    pFile = fopen("data.dat", "r");
    int c;
    while(c != 'I')
    {
        c = fgetc(pFile);
    }
    high = while(c != ' ')
    {
        c = fgetc(pFile);
    }
    printf("%i\n", high);
    if(c == ' '){puts("we read until 1st line space");}
    else{puts("we didn't read until 1st line space");}
    fclose(pFile);
    return 0;
}

high 被分配给一个 while 循环,因为我们可能会得到更大的数字,比如 10,但是这样做会产生错误。如何从文本文件中的值分配整数?

4

1 回答 1

1

改用fscanf()

unsigned short i[2];
/* fscanf() returns number of successful assignments made,
   which must be 2 in this case. */
if (fscanf(pFile, "HI%hu LO%hu", &i[0], &i[1]) == 2)
{
}

如果文件有多行,则用于fgets()逐行读取并用于sscanf()从每行中提取整数值。

始终检查 IO 操作的结果,例如fopen()不返回的结果。NULL

于 2013-05-24T15:18:38.530 回答