c - 从文件中的一行读取任意数量的以空格分隔的字符

标签 c fgets strtok

我有一个文件,其中一行有任意数量的数字,可以作为整数读取。在一个最小的、可重现的示例中,我创建了一个文件 test.dat,其中仅包含以下行:

 1 2 3 4

然后我尝试使用 fgetsstrtok 来实现这一点:

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

int main(){

FILE* fileptr;

fileptr = fopen("test.dat","r");
char line[500];
char *token;

int array[20];
int i = 0;

fgets(line,300,fileptr);

token = strtok(line," ");
array[i] = atoi(token);
printf("%d\n", array[i]);
i++;

while(token != NULL){
    token = strtok(line," ");
    array[i] = atoi(token);
    printf("%d\n", array[i]);
    i++;
}

return 0;
}

但这会导致打印 21 行 1,然后是 632 行 0。最后,它给出了一个段错误,因为 i 大于 20,即为 array 分配的空间。我不明白的是为什么要打印 600 多行,以及为什么我永远无法读取文件中超出数字 1 的内容。我错过了什么?

注意:我更喜欢使用 fgets 继续读取文件,因为这将是对读取整个文件的现有子例程的简单修改。

最佳答案

一些事情:

  • 您没有将循环限制在 array
  • 的容量范围内
  • 您的循环结构不正确。所有的存储都应该在循环内完成;异常值先验不需要存在。
  • 您在循环中调用 strtok 是错误的。 strtok 初始开始的 continuation 应该将 NULL 指定为第一个参数。请参阅 strtok 的文档获取更多信息和使用示例。

这里有一个解决这些问题的例子:

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

int main()
{
    FILE* fileptr = fopen("test.dat","r");
    if (fileptr == NULL)
    {
        perror("Failed to open file: ");
        return EXIT_FAILURE;
    }

    char line[500];
    int array[20];
    const size_t max_size = sizeof array / sizeof *array;
    size_t i = 0;

    if (fgets(line,300,fileptr))
    {
        char *token = strtok(line," ");
        while (i < max_size && token != NULL)
        {
            array[i] = atoi(token);
            printf("%d\n", array[i]);
            ++i;
            token = strtok(NULL, " ");
        }

        // use array and i for whatever you needed
    }

    return EXIT_SUCCESS;
}

输出

1
2
3
4

关于c - 从文件中的一行读取任意数量的以空格分隔的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46103935/

相关文章:

c - fgets() 在返回 NULL 和返回正确值之间随机变化

c - 检测 char 数组中有多少行

C: 2D-Array 没有从一开始就打印出来

c - posix信号量问题

在 typedef 中使用指针调用变量

c - 为什么在这段代码中,fgets 不应该返回 null?

c - 标准I/O流——fgets()缓冲类型

c - 如何在不加载图像的情况下在opencv上绘制矩形/圆形

c - 我有一个字符串 str,它有两个数组(可以更多),我想将它们转换为 C 中的整数数组

c++ - 从字符串中提取数字/数字范围的复杂算法