c - 读取文件。如何将字符串放入字符数组?

标签 c

我正在读取文件并将信息放入数组中供以后使用。 我必须打开然后阅读并关闭。

我完成了前 3 件事并且效果很好。但我对如何继续下一部分感到困惑。另外我怎么知道我什么时候到达文件末尾。我知道这个有多长,因为我做到了。但是,如果我要运行一个未知文件,我将不知道其中有多少文件。

我现在的主要问题是我需要读取最后一个文件的字符串。它会这样做,但它会返回它从文件中提取的最后一个。二维数组是否适合用于字符串,我将如何执行此操作。

int main(void)
{   
    FILE * pFile;
    char buf[40];
    int x[80];
    float y[80];
    int z[80];
    char str[40];


    pFile = fopen("testint.dat", "r");
    if (pFile != NULL)
    {
        int i = 0;
        for ( i = 0; i < 5; i++)
        {
            fgets(buf, 40, pFile);
            x[i] = atoi(buf);

            fgets(buf, 40, pFile);
            y[i] = atof(buf);

            fgets(buf, 40, pFile);
            z[i] = buf[0];

            fgets(str, 40, pFile);
            str[strlen(str) - 1] = '\0';

            printf("\n %s \n", str);

            printf("\n %i \n", x[i]);
            printf("\n %f \n", y[i]);
            printf("\n %c \n", z[i]);
        }

    }

    printf("\n\n %s \n", str);
    printf(" %i \n", x[0]);
    printf(" %f \n", y[1]);
    printf(" %c \n", z[2]);
    system("pause");

}

这里还有文件信息:

1 
1.1
a
aaaa
2 
2.2
b
bbbb
3 
3.3
c
cccc
4 
4.4
d
dddd
5 
5.5
e
eeee

注意:到目前为止,代码没有返回错误。更多的是我如何继续的问题。 (还有任何可以帮助我的人,我欠你一杯啤酒)

最佳答案

But if i was to run a unknown file i wouldn't know how many are in it.

替换

int i = 0;
for ( i = 0; i < 5; i++)
{
    fgets(buf, 40, pFile);
    x[i] = atoi(buf);

    fgets(buf, 40, pFile);
    y[i] = atof(buf);

    fgets(buf, 40, pFile);
    z[i] = buf[0];

    fgets(str, 40, pFile);
    str[strlen(str) - 1] = '\0';

    printf("\n %s \n", str);

    printf("\n %i \n", x[i]);
    printf("\n %f \n", y[i]);
    printf("\n %c \n", z[i]);
}

int i = 0;
while (fgets(buf, 40, pFile))
{
    x[i] = atoi(buf);

    fgets(buf, 40, pFile);
    y[i] = atof(buf);

    fgets(buf, 40, pFile);
    z[i] = buf[0];

    fgets(str, 40, pFile);
    str[strlen(str) - 1] = '\0';

    printf("\n %s \n", str);

    printf("\n %i \n", x[i]);
    printf("\n %f \n", y[i]);
    printf("\n %c \n", z[i]);
    i++;
}

避免使用像40这样的魔数(Magic Number),使用sizeof(buf)

关于c - 读取文件。如何将字符串放入字符数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22420888/

相关文章:

C 宏问题 : redefinition of functions/structure

c - 为什么这个指针操作代码会产生 33554432?

c - GetFileSizeEx 在 System32 目录上返回不正确的值

C 使用 fgets 获取带空格、长度未知的字符串

c - 如何将 ./a.out 的结果存储到文本文件

c - 带参数函数的 printf 返回指向 char 的指针

c - 在 linux 中,获取窗口类 raise "X Error of failed request: BadWindow (invalid Window parameter)"

c - Linux 字符设备模块 : Why do we need both *owner and MOD_INC_USE_COUNT?

c++ - 如何简洁地将一个数组的范围分配给另一个数组的范围?

c - 在文本文件中查找关键字